zoukankan      html  css  js  c++  java
  • 采用 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();       // 关闭文档
        }
    }
  • 相关阅读:
    BZOJ 2752: [HAOI2012]高速公路(road)
    codevs 1979 第K个数
    洛谷 P2680 运输计划
    hdu 3501 Calculation 2
    POJ 2417 Discrete Logging
    比较数组和字典
    js事件之event.preventDefault()与event.stopPropagation()用法区别
    alert
    js基本类型的包装对象
    js取自定义data属性
  • 原文地址:https://www.cnblogs.com/hapday/p/8883148.html
Copyright © 2011-2022 走看看