自己做了一个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; //纵向位置自己试下就行
其它的都很简单了。
页面更新:2024-04-13
本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828
© CopyRight 2020-2024 All Rights Reserved. Powered By 71396.com 闽ICP备11008920号-4
闽公网安备35020302034903号