如何在PDF文档的所有页面上插入背景图片?

11

我需要一份C#示例代码,可以在已完成的PDF文档的所有页面上插入背景图片。我正在使用iTextSharp库。

1个回答

28

你可以尝试这样做:

void makePDF()
{
    Response.ContentType = "application/pdf";

    Response.AddHeader("content-disposition", "attachment;filename=test.pdf");

    Response.Cache.SetCacheability(HttpCacheability.NoCache);

    string imageFilePath = Server.MapPath(".") + "/images/test.jpg";

    iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(imageFilePath);

    // Page site and margin left, right, top, bottom is defined
     Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);

    //Resize image depend upon your need
    //For give the size to image
     jpg.ScaleToFit(3000, 770);

    //If you want to choose image as background then,

    jpg.Alignment = iTextSharp.text.Image.UNDERLYING;

    //If you want to give absolute/specified fix position to image.
    jpg.SetAbsolutePosition(7, 69);

    PdfWriter.GetInstance(pdfDoc, Response.OutputStream);

    pdfDoc.Open();

    pdfDoc.NewPage();

    Paragraph paragraph = new Paragraph("this is the testing text for demonstrate the image is in background \n\n\n this is the testing text for demonstrate the image is in background");

    pdfDoc.Add(jpg);

    pdfDoc.Add(paragraph);

    pdfDoc.Close();

    Response.Write(pdfDoc);

    Response.End();
 }

1
我无法使用 Response。也许我需要连接某个命名空间? - roman
我认为你应该像这样添加 using iTextSharp.text 和 using iTextSharp.text.pdf。我不确定。 - Soner Gönül
我认为他只是想将其写入文件中。 - Mark Storer
4
这个解决方案只在第一页添加了背景图片。如何将背景添加到每一页呢? - spadelives
有更新了吗? - ahmednawazbutt

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接