Java converts long image to PDF output

When the picture is very long, put it into the PDF, you need to calculate the length of the page.

Import the jar package:

<dependency>
      <groupId>com.lowagie</groupId>
      <artifactId>itext</artifactId>
      <version>2.1.7</version>
</dependency>

code:



import com.lowagie.text.Document;
import com.lowagie.text.Image;
import com.lowagie.text.PageSize;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.PdfWriter;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileOutputStream;

/*
图片转成pdf工具类
 */
@Slf4j
public class ImageToPdfUtils {
    // 输出宽度适配A4纸宽度
    public static float width = PageSize.A4.getWidth();

    /**
     * imgFilePath:图片路径
     * pdfFilePath:pdf输出位置
     */
    public static File imageToPdf(String imgFilePath, String pdfFilePath) {

        Document doc = null;
        try {
            // 获取图片
            Image image = Image.getInstance(imgFilePath);
            // 计算图片等比压缩比例: 统一按照宽度压缩 这样来的效果是,如果有多张图片,所有图片的宽度是相等的
            float percent = width / image.getWidth() * 100;
            image.scalePercent(percent); // 1个参数:宽高都是同比例压缩。 2个参数:宽高各自比例压缩。
            image.setAlignment(Image.MIDDLE);
            // 根据宽高比,计算PDF页面高度
            Rectangle rectangle = new Rectangle(width, width / image.getWidth() * image.getHeight());
            log.info("getWidth:{},getHeight:{}", rectangle.getWidth(), rectangle.getHeight());
            doc = new Document(rectangle, 0, 0, 0, 0);
            PdfWriter.getInstance(doc, new FileOutputStream(pdfFilePath));
            doc.open();
            doc.newPage();
            doc.add(image);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                doc.close();
            } catch (Exception e) {
            }
        }

        // 返回生成的PDF文件
        File mOutputPdfFile = new File(pdfFilePath);
        if (!mOutputPdfFile.exists()) {
            mOutputPdfFile.deleteOnExit();
            return null;
        }
        return mOutputPdfFile;
    }
}

Guess you like

Origin blog.csdn.net/kaiyuantao/article/details/131001953