I am trying to add a watermark text with font Helvitica to a simple PDF using one of the examples provided in the IText examples site (https://developers.itextpdf.com/examples/stamping-content-existing-pdfs/clone-watermark-examples), but for some reason the PDF is not showing the font properly in the PDF.
I looked at the pdf property fonts and it seems the font is not embedded to the PDF.
I am using itext 7.0.8 version.
Am I doing some thing wrong here.
My Code:
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();
}
}
If I change the line:
PdfCanvas under = new PdfCanvas(pdfDoc.getFirstPage().newContentStreamBefore(), new PdfResources(), pdfDoc);
To
PdfCanvas over = new PdfCanvas(pdfDoc.getFirstPage());
the font is being embedded to the PDF..
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…