700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > itext 导出pdf 图片太大

itext 导出pdf 图片太大

时间:2020-04-26 02:05:11

相关推荐

itext 导出pdf 图片太大

学习了使用com.Lowagie.itext导出html的内容到导出pdf。会遇到图片太多,导出的时候显示的图片不全,这时候要怎么处理呢?

处理:

图片准备:

back6:

back1:

现象:

导出的图片只有一部分.

因为太宽了,才会被截取,宽度在范围内,高度不影响导出。

要如何缩小图片呢?

<img src=\"F:/temp/back5.jpg\"alt=\"\"width=\"3200\"height=\"1200\"/>

在调整图片的宽度的时候,高度也会跟着变化:

<img src=\"F:/temp/back5.jpg\"alt=\"\"width=\"550\"height=\"1200\"/>

调整到550左右,可以完整显示,但是左右间距有些差别,再缩小写到530

这样左右两边的间距就差不多。我们就可以530为标准进行设置了

代码:

public class ItextPdfBigImageUse {private final static int FONT_NORMAL = Font.NORMAL;private final static float IMG_WIDTH = 530F;public static void main(String[] args) {String value = "<p>图片导出</p>\n<p>&nbsp;</p>\n<p>啦啦</p>\n<p>&nbsp;</p>\n<p>&nbsp;</p>\n<p>" +"<img src=\"F:/temp/back5.jpg\" alt=\"\" width=\"3200\" height=\"1200\" /></p>\n<p>&nbsp;</p>\n<p>发放</p>\n<p>&nbsp;</p>\n<p><img src=\"F://temp//back1.jpg\" alt=\"\" width=\"300\" height=\"108\" /></p>\n<p>第三方</p>\n<p>&nbsp;</p>";htmlToPdf(value, "d://exportFile//y"+System.currentTimeMillis()+".pdf");}public static void htmlToPdf(String content, String pdfPath) {Document document = new Document();try {BaseFont bfChinese = BaseFont.createFont(ResourceUtils.getFile("classpath:static/Fonts/simfang.ttf").getAbsolutePath(),BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);StyleSheet styleSheet = new StyleSheet();styleSheet.loadTagStyle("body", "leading", "16,0");PdfWriter.getInstance(document, new FileOutputStream(pdfPath));document.open();List htmlList = HTMLWorker.parseToList(new StringReader(content), styleSheet);Paragraph context = new Paragraph();context.setKeepTogether(false);Font FontChinese = new Font(bfChinese, 10, FONT_NORMAL);for (Object aHtmlList : htmlList) {Element e = (Element) aHtmlList;System.out.println(e.type() + e.getChunks().toString() + ": "+ e.toString());int type = e.type();if(type == 12){ // 文本和图片List chunks = e.getChunks();Chunk chunk = (Chunk) chunks.get(0);HashMap attributes = chunk.getAttributes();if(MapUtils.isEmpty(attributes)){ // 文本context = new Paragraph(chunk.getContent(), FontChinese);context.setKeepTogether(false);context.add(e);}else{ // 图片Image image = chunk.getImage();float width = image.getWidth();if(width > IMG_WIDTH){//统一按照宽度压缩int percent=getPercentByWidth(width);System.out.println(percent);//按百分比显示图片的比例image.scalePercent(percent);//表示是原来图像的比例;}// image.scaleAbsolute(255.0f, 300.0f); // 固定比例压缩context.add(image);}document.add(context);}else if( type == 23){ // 表格PdfPTable table = (PdfPTable) aHtmlList;document.add(table);}}document.close();System.out.println("ok");}catch(Exception e) {e.printStackTrace();}}/*** 按照图片固定宽度压缩*/private static int getPercentByWidth(float width){float p2=IMG_WIDTH/width*100;return Math.round(p2);} }

部分结果:

总结:

使用 com.Lowagie.itext 导出html内容到pdf上,大图片,要进行处理,按比例缩小(scalePercent方法)。如果所有图片都要按固定比例缩小,使用scaleAbsolute方法。

按固定比例压缩 image.scaleAbsolute(255.0f, 300.0f);

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。