![](/img/trans.png)
[英]PDAnnotationTextMarkup missing when rendering a pdf page to image PDFBox Java
[英]Text is missing when converting pdf file into image in java using pdfbox
我想將PDF頁面轉換為圖像文件。 使用java將PDF頁面轉換為圖像時,文本丟失。
碼:
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.List;
import javax.imageio.ImageIO;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
public class ConvertPDFPageToImageWithoutText {
public static void main(String[] args) {
try {
String oldPath = "C:/PDFCopy/46_2.pdf";
File oldFile = new File(oldPath);
if (oldFile.exists()) {
PDDocument document = PDDocument.load(oldPath);
List<PDPage> list = document.getDocumentCatalog().getAllPages();
for (PDPage page : list) {
BufferedImage image = page.convertToImage();
File outputfile = new File("C:/PDFCopy/image.png");
ImageIO.write(image, "png", outputfile);
document.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
由於您使用的是PDFBox,請嘗試使用PDFImageWriter.writeToImage而不是PDPage.convertToImage。 這篇文章似乎與你想要做的事情有關。
我有同樣的問題。 我發現了一篇文章(不幸的是記不住在哪里因為我讀了數百篇文章)。 有一位作者抱怨說,在將Java版本更新到7.21之后,PDFBox中出現了這樣的問題。 所以我使用的是7.17,它對我有用:)
使用最新版本的PDFBox(我使用2.0.9)並從此處添加JAI Image I / O依賴項。 這是JAVA 7上的示例運行代碼。
public void pdfToImageConvertorUsingPdfBox(String inputPdfPath) throws Exception {
File sourceFile = new File(inputPdfPath);
String formatName = "png";
if (sourceFile.exists()) {
PDDocument document = PDDocument.load(sourceFile);
PDFRenderer pdfRenderer = new PDFRenderer(document);
int count = document.getNumberOfPages();
for (int i = 0; i < count; i++) {
BufferedImage image = pdfRenderer.renderImageWithDPI(i, 200, ImageType.RGB);
String output = FilenameUtils.removeExtension(inputPdfPath) + "_" + (i + 1) + "." + formatName;
ImageIO.write(image, formatName, new File(output));
}
document.close();
} else {
logger.error(sourceFile.getName() + " File not exists");
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.