简体   繁体   English

如何在iText生成的PDF的标题中添加图像?

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

I'm using iText to generate a PDF. 我正在使用iText生成PDF。 I created a custom PdfPageEventHelper to add a header (and footer) to each page. 我创建了一个自定义PdfPageEventHelper,以向每个页面添加页眉(和页脚)。

My problem is I don't know how to add the image so it is displayed in the "header box". 我的问题是我不知道如何添加图像,以使其显示在“页眉框”中。 I only know how to add the image to the document content itself (if that makes sense). 我只知道如何将图像添加到文档内容本身(如果这是有道理的)。

Here's some code snippets ... 这是一些代码片段...

public static void main(String[] args) {
  Rectangle headerBox = new Rectangle(36, 54, 559, 788);
  /* ... */
  Document document = new Document(PageSize.A4, 36, 36, 154, 54);
  PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(FILENAME));
  HeaderFooter event = new HeaderFooter();
  writer.setBoxSize("headerBox", headerBox);
  writer.setPageEvent(event);
  document.open();
  addContent();
  document.close();
}

static class HeaderFooter extends PdfPageEventHelper {

  public void onEndPage(PdfWriter writer, Document document) {
    Rectangle rect = writer.getBoxSize("headerBox");
    // add header text
    ColumnText.showTextAligned(writer.getDirectContent(),
      Element.ALIGN_RIGHT, new Phrase("Hello", fontHeader1),
      rect.getLeft(), rect.getTop(), 0);

    // add header image
    try {
      Image img = Image.getInstance("c:/mylogo.PNG");
      img.scaleToFit(100,100);
      document.add(img);
    } catch (Exception x) {
      x.printStackTrace();
    }

  }

}

Any suggestions on the appropriate way to add the image to the header are greatly appreciated!! 任何有关将图像添加到标题的适当方式的建议都将不胜感激!!

Rob

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. 这将导致PDF膨胀,因为图像字节的添加次数将与页面一样多。 Please create the Image object outside the onEndPage() method, and reuse it. 请在onEndPage()方法之外创建Image对象,然后重用它。 This way, the image bytes will be added to the PDF only once. 这样,图像字节将仅添加到PDF一次。
  2. As documented, the Document passed to the onEndPage() method as a parameter should be considered as a read-only parameter. 如文档所述, onEndPage() Document作为参数传递给onEndPage()方法,应将其视为只读参数。 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) . 与使用new Document(PageSize.A4, 36, 36, 154, 54)创建的对象不同。 In reality, it's an instance of a PdfDocument class created internally by the PdfWriter instance. 实际上,它是由PdfWriter实例在内部创建的PdfDocument类的实例。 To add an image, you need to get the PdfContentByte from the writer, and add the image using addImage() . 要添加图像,您需要从PdfContentByte获取PdfContentByte ,然后使用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 . 通过阅读我的《 iText in Action》,您可以节省大量时间。

Can you try 你能试一下吗

img.setAbsolutePosition(10, 10);
writer.getDirectContent().addImage(img);

instead of 代替

document.add(img);

inside onPageEnd ? onPageEnd里面?

I've set abolute positions and alignment to the image (in this case I placed my image in the header) 我已经设定了图片的位置和对齐方式(在这种情况下,我将图片放在了标题中)

    try {
        Image img = Image.getInstance("url/logo.png");
        img.scaleToFit(100,100);  
        img.setAbsolutePosition((rect.getLeft() + rect.getRight()) / 2 - 45, rect.getTop() - 50);
        img.setAlignment(Element.ALIGN_CENTER);          
        writer.getDirectContent().addImage(img);
      } catch (Exception x) {
        x.printStackTrace();
      }

I've also adjusted the the document margins in order to have delimited space in the header and footer of the document. 我还调整了文档页边距,以在文档的页眉和页脚中留出一定的空间。

document.setMargins(20, 20, 100, 100);

A generic solution to add image at the top of the page. 在页面顶部添加图像的通用解决方案。 We can do it by positing image to the top also. 我们也可以通过将图像放置在顶部来实现。 it may fix your requirement 它可能会解决您的要求

public static void main(String[] args) throws MalformedURLException, IOException, DocumentException {
      Document document = new Document();
        try {
            PdfWriter.getInstance(document,
                    new FileOutputStream("HelloWorld.pdf"));
            document.open();

            //
            // Scale the image to a certain percentage
            //
            String filename = "image.jpg";
            Image image = Image.getInstance(filename);
            image = Image.getInstance(filename);
            image.scalePercent(200f);
            image.setAbsolutePosition(0, (float) (PageSize.A4.getHeight() - 20.0));
            System.out.println(image.getScaledHeight());
            document.add(image);

            //
            // Scales the image so that it fits a certain width and
            // height
            //
            image.scaleToFit(100f, 200f);
            document.add(image);
            document.add(new Chunk("This is chunk 3. "));
            System.out.println("created");
        } catch (DocumentException | IOException e) {
            e.printStackTrace();
        } finally {
            document.close();
        }
}

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM