在生成PDF 的时候,虽然可以在页面中设置背景图。
但有些内容过长夸页面的时候,就很难设置背景图,变成了空白背景的页面!
以下是重新生成每一页 PDF 背景图功能代码!
public void SetPdfBackground(string pdfFilePath) { //重新生成的 PDF 的路径 string destFile = HttpContext.Current.Server.MapPath("sample.pdf"); //create new pdf document FileStream stream = new FileStream(destFile, FileMode.Create, FileAccess.ReadWrite); PdfReader reader = new PdfReader(pdfFilePath); //read pdf stream PdfStamper stamper = new PdfStamper(reader, stream); string imagePage = HttpContext.Current.Server.MapPath("../images/2012/bg2.png"); System.Drawing.Image image = System.Drawing.Image.FromFile(imagePage); var img = Image.GetInstance(image, System.Drawing.Imaging.ImageFormat.Png); img.SetAbsolutePosition(0, 0); int totalPage = reader.NumberOfPages; for (int current = 1; current <= totalPage; current++) { var canvas = stamper.GetUnderContent(current); var page = stamper.GetImportedPage(reader, current); canvas.AddImage(img); } stamper.Close(); reader.Close(); }