我正在使用下面的代码将 PDF 转换为 PNG 图像。
Document document = new Document();
try {
document.setFile(myProjectPath);
System.out.println("Parsed successfully...");
} catch (PDFException ex) {
System.out.println("Error parsing PDF document " + ex);
} catch (PDFSecurityException ex) {
System.out.println("Error encryption not supported " + ex);
} catch (FileNotFoundException ex) {
System.out.println("Error file not found " + ex);
} catch (IOException ex) {
System.out.println("Error handling PDF document " + ex);
}
// save page caputres to file.
float scale = 1.0f;
float rotation = 0f;
// Paint each pages content to an image and write the image to file
InputStream fis2 = null;
File file = null;
for (int i = 0; i < 1; i++) {
BufferedImage image = (BufferedImage) document.getPageImage(i,
GraphicsRenderingHints.SCREEN,
Page.BOUNDARY_CROPBOX, rotation, scale);
RenderedImage rendImage = image;
// capture the page image to file
try {
System.out.println("\t capturing page " + i);
file = new File(myProjectActualPath + "myImage.png");
ImageIO.write(rendImage, "png", file);
fis2 = new BufferedInputStream(new FileInputStream(myProjectActualPath + "myImage.png"));
} catch (IOException ioe) {
System.out.println("IOException :: " + ioe);
} catch (Exception e) {
System.out.println("Exception :: " + e);
}
image.flush();
}
myProjectPath
是 pdf 文件的路径。
问题是我的 pdf 图像大小为 305 KB。当我使用上面的代码转换图像时,图像大小为 5.5 MB,这是意外的。发生这种情况有什么原因吗?有办法压缩这个吗?如果我找到压缩尺寸的解决方案(通过减小像素尺寸),也可以。
注意:对于其他 pdf 文件,图像大小为 305 KB。一个 PDF 文件会发生这种情况,但不确定为什么会发生这种情况。
编辑 1
我使用 jar 文件作为
icepdf-core.jar
icepdf-viewer.jar
我拥有的进口是
import org.icepdf.core.exceptions.PDFException;
import org.icepdf.core.exceptions.PDFSecurityException;
import org.icepdf.core.pobjects.Document;
import org.icepdf.core.pobjects.Page;
import org.icepdf.core.util.GraphicsRenderingHints;
最佳答案
您可以从 pdf 中提取图像(使用 PDFBox 的示例):
List<PDPage> pages = document.getDocumentCatalog().getAllPages();
for(PDPage page : pages) {
Map<String, PDXObjectImage> images = page.getResources().getImages();
for(PDXObjectImage image : images.values()){
//TODO: write image to disk
}
}
或者/并且您可能希望将它们以 jpg 格式保存到磁盘,因为 jpg 优于压缩而不是 png。
您甚至可以识别原始图像的格式,并通过调用以下命令在写入磁盘时使用该格式:
image.getSuffix();
关于java - PDF 到图像转换大尺寸图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12578889/