近期在項目中使用到了大量的報表開發(fā),需要將html頁面中的表格內(nèi)容導(dǎo)出到pdf word excel和圖片,前三者都比較好實現(xiàn)。唯獨后者生成圖片使用ImageIo操作時生成的圖片有點慘不忍睹。經(jīng)過大量google后發(fā)現(xiàn),pdfbox這個組件不錯,可以將pdf文件輕松生成圖片。這不問題解決了,但在使用過程中不然,受到了很多致命性的打擊。pdfbox在處理中文pdf的時候就會表現(xiàn)的比較脆弱點。但對英文版的pdf導(dǎo)出圖片,那是杠杠的。盡管這樣,還是記錄一下,畢竟這方面的資料很少。我?guī)缀跛驯榱苏麄€google,baidu才搜集到那么一點點資料。這里跟大家分享下。
所依賴的JAR:
commons-logging-1.1.1.jar
fontbox-1.2.1.jar
pdfbox-1.2.1.jar
示例代碼:
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.future.pdfbox.image;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;

public class ExtractImages
{
public static void main(String[] args) throws IOException {
PDDocument doc = PDDocument.load("F:\\1.pdf");
int pageCount = doc.getPageCount();
System.out.println(pageCount);
List pages = doc.getDocumentCatalog().getAllPages();
for(int i=0;i<pages.size();i++){
PDPage page = (PDPage)pages.get(i);
BufferedImage image = page.convertToImage();
Iterator iter = ImageIO.getImageWritersBySuffix("jpg");
ImageWriter writer = (ImageWriter)iter.next();
File outFile = new File("C:/"+i+".jpg");
FileOutputStream out = new FileOutputStream(outFile);
ImageOutputStream outImage = ImageIO.createImageOutputStream(out);
writer.setOutput(outImage);
writer.write(new IIOImage(image,null,null));
}
doc.close();
System.out.println("over");
}

}
所依賴的JAR:
commons-logging-1.1.1.jar
fontbox-1.2.1.jar
pdfbox-1.2.1.jar
示例代碼:
























































