how to add an image to my header in iText generated PDF?

后端 未结 4 1393
花落未央
花落未央 2021-01-13 01:39

I\'m using iText to generate a PDF. I created a custom PdfPageEventHelper to add a header (and footer) to each page.

My problem is I don\'t know how to add the imag

4条回答
  •  無奈伤痛
    2021-01-13 02:01

    You are making two major mistakes.

    1. You are creating a new instance of the object for every new page. This will result in a bloated PDF as the image bytes will be added as many times as there as pages. Please create the Image object outside the onEndPage() method, and reuse it. This way, the image bytes will be added to the PDF only once.
    2. As documented, the Document passed to the onEndPage() method as a parameter should be considered as a read-only parameter. It is forbidden to add content to it. It's a different object than the one you created with new Document(PageSize.A4, 36, 36, 154, 54). In reality, it's an instance of a PdfDocument class created internally by the PdfWriter instance. To add an image, you need to get the PdfContentByte from the writer, and add the image using addImage().

    Errors like this can easily be avoided by reading the documentation. You can save plenty of time by reading my book iText in Action.

提交回复
热议问题