采用 ITextPDF 类库测试向 PDF 中加入图片的示例


package com.smbea.image; import com.artup.util.image.ImageUtil; import com.itextpdf.text.*; import com.itextpdf.text.pdf.PdfWriter; import lombok.extern.slf4j.Slf4j; import org.junit.Test; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; /** * <p>采用 ITextPDF 类库测试向 PDF 中加入图片的示例</p> * @author hapday * @date 2018/4/19 / @time 14:39 */ @Slf4j public class PdfImageTest { @Test public void imageTest(){ Rectangle rectangle = new Rectangle(PageSize.A4);       // 设置 PDF 纸张矩形,大小采用 A4
        rectangle.setBackgroundColor(BaseColor.ORANGE);       // 设置背景色 //创建一个文档对象,设置初始化大小和页边距
        Document document = new Document(rectangle, 10, 10, 10, 10);     // 上、下、左、右页间距
 String pdfPath = "D://pdfImage_test.pdf";   // PDF 的输出位置
        try { PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(pdfPath)); } catch (DocumentException e) { log.error("将文档对象设置到文件输出流中 - 出错了!", e); } catch (FileNotFoundException e) { log.error("未找到指定的文件!", e); } document.open(); // 打开文档对象
 String imagePath = "F:\\IdeaProjects\\artup-mobile\\src\\main\\webapp\\image\\Docker.jpg";      // 图片的绝对路径
        Image image = null;     // 声明图片对象
        try { image = Image.getInstance(imagePath);       // 取得图片对象
        } catch (BadElementException | IOException e) { log.error("实例化【图片】 - 失败!", e); return; } image.scaleAbsolute(ImageUtil.getImageWidth(imagePath), ImageUtil.getImageHeight(imagePath)); image.setAbsolutePosition(10, 20);      // (以左下角为原点)设置图片的坐标

        try { document.add(image); } catch (DocumentException e) { log.error("将图片对象加入到文档对象中时 - 出错了!", e); } document.close(); // 关闭文档
 } }

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM