Может ли кто-нибудь дать мне пример о том, как использовать Apache PDFBox для преобразования PDF в разные изображения (по одной на каждую страницу в формате pdf). Спасибо заранее
Apache PDFBox конвертировать PDF в изображения
Ответ 1
Решение для версий 1.8. *:
PDDocument document = PDDocument.loadNonSeq(new File(pdfFilename), null);
List<PDPage> pdPages = document.getDocumentCatalog().getAllPages();
int page = 0;
for (PDPage pdPage : pdPages)
{
++page;
BufferedImage bim = pdPage.convertToImage(BufferedImage.TYPE_INT_RGB, 300);
ImageIOUtil.writeImage(bim, pdfFilename + "-" + page + ".png", 300);
}
document.close();
Не забудьте прочитать страницу с зависимостями 1.8 перед сборкой.
Решение для версии 2.0:
PDDocument document = PDDocument.load(new File(pdfFilename));
PDFRenderer pdfRenderer = new PDFRenderer(document);
for (int page = 0; page < document.getNumberOfPages(); ++page)
{
BufferedImage bim = pdfRenderer.renderImageWithDPI(page, 300, ImageType.RGB);
// suffix in filename will be used as the file format
ImageIOUtil.writeImage(bim, pdfFilename + "-" + (page+1) + ".png", 300);
}
document.close();
Класс ImageIOUtil находится в отдельной загрузке/артефакте (pdf-tools). Прежде чем приступить к сборке, прочитайте страницу зависимостей 2.0, вам понадобятся дополнительные файлы jar для PDF файлов с изображениями jbig2, для сохранения изображений в формате tiff и чтения зашифрованных файлов.
Убедитесь, что вы используете последнюю версию той версии JDK, которую вы используете, то есть, если вы используете jdk8, то не используйте версию 1.8.0_5, используйте 1.8.0_191 или любую последнюю версию на момент чтения. Ранние версии были очень медленными.
Ответ 2
Я попробовал это сегодня с PdfBox 2.0.15.
import org.apache.pdfbox.pdmodel.*;
import org.apache.pdfbox.rendering.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
public static void PDFtoJPG (String in, String out) throws Exception
{
PDDocument pd = PDDocument.load (new File (in));
PDFRenderer pr = new PDFRenderer (pd);
BufferedImage bi = pr.renderImageWithDPI (0, 300);
ImageIO.write (bi, "JPEG", new File (out));
}
Ответ 3
Без каких-либо дополнительных зависимостей вы можете просто использовать класс PDFToImage
, уже включенный в PDFBox
.
Котлин:
PDFToImage.main(arrayOf<String>("-outputPrefix", "newImgFilenamePrefix", existingPdfFilename))
other config opts: https://pdfbox.apache.org/docs/2.0.8/javadocs/org/apache/pdfbox/tools/PDFToImage.html
Ответ 4
public class PDFtoJPGConverter {
public List<File> convertPdfToImage(File file, String destination) throws Exception {
File destinationFile = new File(destination);
if (!destinationFile.exists()) {
destinationFile.mkdir();
System.out.println("DESTINATION FOLDER CREATED -> " + destinationFile.getAbsolutePath());
}else if(destinationFile.exists()){
System.out.println("DESTINATION FOLDER ALLREADY CREATED!!!");
}else{
System.out.println("DESTINATION FOLDER NOT CREATED!!!");
}
if (file.exists()) {
PDDocument doc = PDDocument.load(file);
PDFRenderer renderer = new PDFRenderer(doc);
List<File> fileList = new ArrayList<File>();
String fileName = file.getName().replace(".pdf", "");
System.out.println("CONVERTER START.....");
for (int i = 0; i < doc.getNumberOfPages(); i++) {
// default image files path: original file path
// if necessary, file.getParent() + "/" => another path
File fileTemp = new File(destination + fileName + "_" + i + ".jpg"); // jpg or png
BufferedImage image = renderer.renderImageWithDPI(i, 200);
// 200 is sample dots per inch.
// if necessary, change 200 into another integer.
ImageIO.write(image, "JPEG", fileTemp); // JPEG or PNG
fileList.add(fileTemp);
}
doc.close();
System.out.println("CONVERTER STOPTED.....");
System.out.println("IMAGE SAVED AT -> " + destinationFile.getAbsolutePath());
return fileList;
} else {
System.err.println(file.getName() + " FILE DOES NOT EXIST");
}
return null;
}
public static void main(String[] args) {
try {
PDFtoJPGConverter converter = new PDFtoJPGConverter();
Scanner sc = new Scanner(System.in);
System.out.print("Enter your destination folder where save image \n");
// Destination = D:/PPL/;
String destination = sc.nextLine();
System.out.print("Enter your selected pdf files name with source folder \n");
String sourcePathWithFileName = sc.nextLine();
// Source Path = D:/PDF/ant.pdf,D:/PDF/abc.pdf,D:/PDF/xyz.pdf
if (sourcePathWithFileName != null || sourcePathWithFileName != "") {
String[] files = sourcePathWithFileName.split(",");
for (String file : files) {
File pdf = new File(file);
System.out.print("FILE:>> "+ pdf);
converter.convertPdfToImage(pdf, destination);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
====================================
Здесь я использую Apache pdfbox-2.0.8, commons-logging-1.2 и fontbox-2.0.8 Library
СЧАСТЛИВЫЕ КОДИРОВАНИЕ :)