iText 生成的 PDF -> 将 PDF 保存到本地驱动器后文本丢失

PDF generated by iText -> text missing after saving PDF to local drive

我正在使用 itText 在 HttpServlet 中生成 PDF 文件。在 canvas 上添加文本。如果我打开 url,PDF 会正确显示文本。此外,如果我直接从浏览器打印它,则文本在打印纸上可见。另一方面,如果我下载 PDF,则文本不再显示(图像仍然显示)。可在此处查看 PDF:http://www.vegantastic.de/pdfTest

我的代码如下所示:

Document document = new Document();
// step 2
ByteArrayOutputStream baos = new ByteArrayOutputStream();
private PdfWriter writer = PdfWriter.getInstance(document, baos);
// step 3
document.open();

Font helvetica = new Font(FontFamily.TIMES_ROMAN, 12);
BaseFont bf_helv = helvetica.getCalculatedBaseFont(false);
PdfContentByte canvas = writer.getDirectContentUnder();
canvas.setFontAndSize(bf_helv, 12);

canvas.showTextAligned(Element.ALIGN_LEFT, "Test TEXT - Why is it missing after download?", 100, 800,0);

document.close();

// setting some response headers
response.setHeader("Expires", "0");
response.setHeader("Cache-Control",
        "must-revalidate, post-check=0, pre-check=0");
response.setHeader("Pragma", "public");
// setting the content type
response.setContentType("application/pdf");
// the contentlength
response.setContentLength(baos.size());
// write ByteArrayOutputStream to the ServletOutputStream
OutputStream os = response.getOutputStream();
baos.writeTo(os);
os.flush();
os.close();

对于这种或这种错误,是否有任何合理的解释?有什么办法可以解决这个问题?

您没有正确添加文本。您正在创建的 PDF 包含严重的语法错误。某些 PDF 查看器会忽略此语法错误并显示文本(这可能是您可以从浏览器打印 PDF 的原因);其他人将不会显示任何内容,因为您正在 外部 文本对象显示文本。

有多种方法可以在绝对位置添加文本。一种方法是自己创建一个文本对象:

canvas.beginText();
canvas.setFontAndSize(bf_helv, 12);
canvas.showTextAligned(Element.ALIGN_LEFT, "Test TEXT - Why is it missing after download?", 100, 800,0);
canvas.endText();

在这种情况下,您需要手动 beginend 文本对象。您的代码中缺少该内容。

另一种方法是让 iText 创建文本对象:

ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT,
    new Phrase("Test TEXT - Why is it missing after download?", new Font(bf_helv, 12)),
    100, 800,0);

这一行相当于上面的四行。

重要提示:

您正在使用这个 canvas:

PdfContentByte canvas = writer.getDirectContentUnder();

但是:如果您的文档包含不透明元素(图像、彩色矩形...),那么您添加的任何文本都将被这些不透明元素覆盖。你确定你不想:

PdfContentByte canvas = writer.getDirectContent();

试试这个

PdfContentByte canvas = writer.getDirectContentUnder();
canvas.saveState();
canvas.beginText();

canvas.setFontAndSize(bf_helv, 12);

canvas.showTextAligned(Element.ALIGN_LEFT, "Test TEXT - Why is it missing after download?", 100, 800,0);

canvas.endText();
canvas.restoreState();