近期在項(xiàng)目中使用到了大量的報(bào)表開(kāi)發(fā),需要將html頁(yè)面中的表格內(nèi)容導(dǎo)出到pdf word excel和圖片,前三者都比較好實(shí)現(xiàn)。唯獨(dú)后者生成圖片使用ImageIo操作時(shí)生成的圖片有點(diǎn)慘不忍睹。經(jīng)過(guò)大量google后發(fā)現(xiàn),pdfbox這個(gè)組件不錯(cuò),可以將pdf文件輕松生成圖片。這不問(wèn)題解決了,但在使用過(guò)程中不然,受到了很多致命性的打擊。pdfbox在處理中文pdf的時(shí)候就會(huì)表現(xiàn)的比較脆弱點(diǎn)。但對(duì)英文版的pdf導(dǎo)出圖片,那是杠杠的。盡管這樣,還是記錄一下,畢竟這方面的資料很少。我?guī)缀跛驯榱苏麄€(gè)google,baidu才搜集到那么一點(diǎn)點(diǎn)資料。這里跟大家分享下。
所依賴(lài)的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");
}

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
























































