gpt4 book ai didi

java - 使用 iText 替换 PDF 中的字体 (Java)

转载 作者:行者123 更新时间:2023-12-01 04:39:18 26 4
gpt4 key购买 nike

我想使用 iText 将 PDF 的所有字体(嵌入字体或其他字体)转换为另一种字体。我知道行高、字距调整和其他一些事情会被搞砸,但我真的不介意输出有多难看。

我已经了解了如何将字体嵌入到现有的 pdf 中 here ,但我不知道如何将文档中的所有现有文本设置为该字体。

我知道这并不像我想象的那么简单。也许从文档中获取所有原始文本并使用新字体创建一个新文档会更容易(同样,布局/可读性对我来说不是问题)

最佳答案

示例EmbedFontPostFacto.java来自 iText in Action — 2nd Edition 第 16 章展示如何嵌入原本未嵌入的字体。核心方法是这样的:

public void manipulatePdf(String src, String dest) throws IOException, DocumentException {
// the font file
RandomAccessFile raf = new RandomAccessFile(FONT, "r");
byte fontfile[] = new byte[(int)raf.length()];
raf.readFully(fontfile);
raf.close();
// create a new stream for the font file
PdfStream stream = new PdfStream(fontfile);
stream.flateCompress();
stream.put(PdfName.LENGTH1, new PdfNumber(fontfile.length));
// create a reader object
PdfReader reader = new PdfReader(RESULT1);
int n = reader.getXrefSize();
PdfObject object;
PdfDictionary font;
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(RESULT2));
PdfName fontname = new PdfName(FONTNAME);
for (int i = 0; i < n; i++) {
object = reader.getPdfObject(i);
if (object == null || !object.isDictionary())
continue;
font = (PdfDictionary)object;
if (PdfName.FONTDESCRIPTOR.equals(font.get(PdfName.TYPE))
&& fontname.equals(font.get(PdfName.FONTNAME))) {
PdfIndirectObject objref = stamper.getWriter().addToBody(stream);
font.put(PdfName.FONTFILE2, objref.getIndirectReference());
}
}
stamper.close();
reader.close();
}

此(没有 fontname.equals(font.get(PdfName.FONTNAME)) 测试)可能是您任务的简单情况的起点。

您必须进行大量有关编码的测试,并添加一些单独的翻译以获得更通用的解决方案。您可能想要研究 PDF 规范的第 9 节文本 ISO 32000-1 为此。

关于java - 使用 iText 替换 PDF 中的字体 (Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16848072/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com