为什么在 Itext7 之前没有使用内容流将字体嵌入到 PDF 中?

Why font is not being embedded to the PDF using content stream before in Itext7?

我正在尝试使用 IText 示例网站 (https://developers.itextpdf.com/examples/stamping-content-existing-pdfs/clone-watermark-examples) 中提供的示例之一将带有 Helvitica 字体的水印文本添加到简单的 PDF,但由于某种原因,PDF 未显示字体正确地在 PDF 中。

我查看了 pdf 属性 字体,该字体似乎未嵌入到 PDF 中。

我使用的是itext 7.0.8版本

我是不是做错了什么。

我的代码:

import java.io.FileNotFoundException;
import java.io.IOException;
import com.itextpdf.io.font.FontConstants;
import com.itextpdf.io.font.FontProgramFactory;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfResources;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.layout.Canvas;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.property.TextAlignment;
import com.itextpdf.layout.property.VerticalAlignment;

public class AddTextToPDF {
    public static void main(String[] args) throws FileNotFoundException, IOException {
        PdfDocument pdfDoc = new PdfDocument(new PdfReader("c:\Development\test.pdf"),
                new PdfWriter("c:\Development\test_result.pdf"));
        PdfCanvas under = new PdfCanvas(pdfDoc.getFirstPage().newContentStreamBefore(), new PdfResources(), pdfDoc);
        PdfFont font = PdfFontFactory.createFont(FontProgramFactory.createFont(FontConstants.HELVETICA));
        Paragraph p = new Paragraph("This watermark is added UNDER the existing content")
                .setFont(font).setFontSize(15);
        new Canvas(under, pdfDoc, pdfDoc.getDefaultPageSize())
                .showTextAligned(p, 297, 550, 1, TextAlignment.CENTER, VerticalAlignment.TOP, 0);
        pdfDoc.close();
    }
}

如果我换行:

PdfCanvas under = new PdfCanvas(pdfDoc.getFirstPage().newContentStreamBefore(), new PdfResources(), pdfDoc);

PdfCanvas over = new PdfCanvas(pdfDoc.getFirstPage());

正在将字体嵌入到 PDF 中..

正如您自己发现的那样,问题与此行有关:

PdfCanvas under = new PdfCanvas(pdfDoc.getFirstPage().newContentStreamBefore(), new PdfResources(), pdfDoc);

问题是您在此处使用了一个 new PdfResources() 对象,该对象以后不会用于任何用途。

您在此 PdfCanvas 构造函数中提供的资源对象是放置您在 canvas 上绘制的内容所需的新资源的地方,例如新的字体资源。

因此,在您的情况下,新字体被添加到一个新的资源对象中,然后该对象无处添加,因此根本不会出现在最终的 pdf 中。所以字体丢失了。

要解决此问题,请改用页面资源。