C#给PDF每一页都加上自己的图片logo标识
当前位置:点晴教程→知识管理交流
→『 技术文档交流 』
自己做了一个PDF说明文件给客户,现在需要在每一页上都加上自己的logo图片,具体操作过程如下: 建项目这些就省略了,直接上代码:using iTextSharp.text.pdf;
using System;
using System.IO;
using System.Windows.Forms;
namespace Pic2PDF
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string path = Application.StartupPath; //源PDF地址
string pdffilename = path + "\\test.pdf"; //加完图片的PDF地址
string pdffilename1 = path + "\\test1.pdf"; //图片文件地址
string picfilename = path + "\\sign.jpg"; //执行操作,加上图片
string r = AddPics(pdffilename, pdffilename1, picfilename);
MessageBox.Show(r);
}
public static string AddPics(string PdfPath, string OutPdfPath, string picpath)
{
try
{
if (File.Exists(OutPdfPath))
{
File.delete(OutPdfPath);
}
PdfReader reader = new PdfReader(PdfPath);
PdfStamper stamp = new PdfStamper(reader, new FileStream(OutPdfPath, FileMode.create));
int n = reader.NumberOfPages;
int i = 0;
PdfContentByte under;
iTextSharp.text.Image im = iTextSharp.text.Image.GetInstance(picpath);
PDFATT att = new PDFATT(PdfPath);
float ww = att.Width();
float hh = att.Height();
float w = im.Width;
float h = im.Height;
float locationx;
float locationy;
locationx = ww - w - 20;
locationy = 50;
im.SetAbsolutePosition(locationx, locationy);
im.ScaleAbsolute(w, h);
while (i < n)
{
i++;
under = stamp.GetOverContent(i);
under.AddImage(im, false);
}
stamp.Close();
reader.Close();
}
catch (Exception ex)
{
return ex.Message;
}
return "ok";
}
class PDFATT
{
PdfReader reader;
public PDFATT(string iPdfFilePath)
{
reader = new PdfReader(iPdfFilePath);
}
public int PageCount()
{
return reader.NumberOfPages;
}
public float Width()
{
return reader.GetPageSize(1).Width;
}
public float Height()
{
return reader.GetPageSize(1).Height;
}
}
}
}我这里设置的是添加到右下角了,位置的代码主要在这个地方PDFATT att = new PDFATT(PdfPath); float ww = att.Width(); //PDF的宽度 float hh = att.Height(); //PDF的高度 float w = im.Width; //图片宽 float h = im.Height; //图片高 float locationx; float locationy; locationx = ww - w - 20; //横向位置自己计算 locationy = 50; //纵向位置自己试下就行 其它的都很简单了。 运行效果如下:该文章在 2023/5/22 9:37:43 编辑过 |
关键字查询
相关文章
正在查询... |