轻松使用apache pdfbox将pdf文件生成图片
近期在项目中使用到了大量的报表开发,需要将html页面中的表格内容导出到pdf word excel和图片,前三者都比较好实现。唯独后者生成图片使用ImageIo操作时生成的图片有点惨不忍睹。经过大量google后发现,pdfbox这个组件不错,可以将pdf文件轻松生成图片。这不问题解决了,但在使用过程中不然,受到了很多致命性的打击。pdfbox在处理中文pdf的时候就会表现的比较脆弱点。但对英文版的pdf导出图片,那是杠杠的。尽管这样,还是记录一下,毕竟这方面的资料很少。我几乎搜遍了整个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");
}
}
转至:http://www.blogjava.net/sxyx2008/archive/2010/07/23/326890.html
页:
[1]