如何使用iText7和pdfHtml缩放背景图像?

时间:2019-12-03 17:04:10

标签: itext7 pdfhtml

我正在尝试升级到最新版本的iText,但遇到了一些问题。当前,我们使用Apache Velocity模板,然后使用iText将结果HTML转换为pdf。

我们有一个大图像(2220 x 3248)作为背景包含在PDF中。我已经将模板缩减为最低限度的测试。

<html>
<head>
  <style type="text/css">
    @page {
      margin-top:57px;
      margin-bottom:50px;
      margin-left: 110px;
      margin-right: 40px;
      padding-top:160px;
      padding-bottom:5px;
      background-image:url('templates/background.png');
      background-size:100% 100%;
      background-position:top left;
    }
  </style>
</head>
<body>

<h1>Background Image Test</h1>

</body>
</html>

然后,我使用以下代码来呈现PDF。

public void render(PdfRendererContext ctx) throws Exception {
  ConverterProperties properties = new ConverterProperties();
  PdfWriter writer = new PdfWriter((OutputStream) ctx.getOutput().getOutput());
  PdfDocument pdf = new PdfDocument(writer);
  properties.setBaseUri("path/to/files");
  HtmlConverter.convertToPdf((String) ctx.getInput().getInput(), pdf, properties);
}

这将转换PDF,我基本上可以得到想要的东西,但是背景图像不再缩放。该图像应该是页面周围的边框,中间是徽标,但是如您所见,该图像比整个页面大得多。 Generated PDF

我尝试了几种不同的方式来更改背景大小,但没有成功。有什么方法可以缩放类似于我需要的背景图像?

1 个答案:

答案 0 :(得分:1)

很遗憾,pdfHTML尚不支持background-size CSS属性。有一个后处理解决方案,可用于通过iText Core将背景图像添加到PDF文档中。因此,您不会在HTML中定义任何背景图片,而只是在后期处理阶段添加它们。以下是代码查找所描述方法的方式:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
// Converting to a memory stream to process the document in memory afterwards before flushing to disk
HtmlConverter.convertToPdf(htmlStream, baos);

PdfDocument pdfDocument = new PdfDocument(new PdfReader(new ByteArrayInputStream(baos.toByteArray())),
        new PdfWriter(new File("C:/path/to/out.pdf")));
ImageData imageData = ImageDataFactory.create("C:/path/to/background.png");
// Page size of the output HTML document
Rectangle pageSize = PageSize.A4;
Image image = new Image(imageData).scaleAbsolute(pageSize.getWidth(), pageSize.getHeight());
for (int i = 1; i <= pdfDocument.getNumberOfPages(); i++) {
    PdfPage page = pdfDocument.getPage(i);
    // newContentStreamBefore just adds some content on the back layer, to be shown behind other content
    PdfCanvas pdfCanvas = new PdfCanvas(page.newContentStreamBefore(), page.getResources(), pdfDocument);
    new Canvas(pdfCanvas, pdfDocument, pageSize).add(image);
}
pdfDocument.close();