用java生成包含图片的PDF

来源:互联网 发布:php两个等号和三个等号 编辑:程序博客网 时间:2024/05/29 03:56

iText包是java生成PDF文件的一个挺好用的工具。

今天初次尝试使用,将代码记录一下。

public void createPdf(String path){File file=new File(path);  String files[];  ArrayList<String> pictures = new ArrayList<String>();files=file.list();  for(int i=0;i<files.length;i++)if(files[i].matches(".+\\.(jpg|gif|png)"))pictures.add(files[i]);Document doc=new Document();try {PdfWriter.getInstance(doc, new FileOutputStream("D:"+File.separator+"root"           +File.separator+"picture.pdf"));doc.open();            float width=doc.getPageSize().getWidth()-75;//取页面宽度并减去页边距for(String temp:pictures){Image tempImage=Image.getInstance(path+File.separator+temp);if(tempImage.getWidth()>width){tempImage.scalePercent(width/tempImage.getWidth()*100);//用页面显示宽度除以图片宽度算出缩小的合适百分比}doc.add(tempImage);}doc.close();} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (DocumentException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (MalformedURLException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} }
从指定的文件夹中取出所有iText可处理的图片文件,然后依次放入PDF中。第一次生成时发现有一个图片过大,超出PDF边界,后来发现有方法可以取出PDF的页面宽度以及图片宽度,用页面宽度减去页边距,然后再根据图片宽度算出应该缩放的百分比,有一个问题要注意,就是缩放后图片宽度不变,只是在PDF中显示的宽度变了。

原创粉丝点击