PDF轉圖檔的需求,如果再iText7有現成的Method可以使用,不過可惜專案的Framework只能支援到iText 5.x ,底下是經測試可運行的,備忘囉!!
AT POM.xml add
<!--PDF to JPG-->
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>1.8.3</version>
</dependency>
Add CLASS Method
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;
//Filetype support jpg, jpeg, png, bmp, gif
public static int ConverPdf2Jpg(String s_path, String s_fname, String Filetype) {
String s_destname = s_fname + ".jpg";
int pageNumber = 1;
try {
String sourceDir = s_path + s_fname + Filetype ;
String destinationDir = s_path;
File sourceFile = new File(sourceDir);
File destinationFile = new File(destinationDir);
if (!destinationFile.exists()) destinationFile.mkdir();
if (sourceFile.exists()) {
PDDocument document = PDDocument.load(sourceDir);
List<PDPage> list = document.getDocumentCatalog().getAllPages();
String fileName = sourceFile.getName().replace(".pdf", "");
for (PDPage page : list) {
BufferedImage image = page.convertToImage();
File outputfile = new File(destinationDir + fileName +"_"+ pageNumber + Filetype );
ImageIO.write(image, "jpg", outputfile);
pageNumber++;
}
document.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return pageNumber ;
}
沒有留言:
張貼留言