将PDF页面大小转为A4格式(itextPdf实现)
1. 引入相关jar包
<!-- https://mvnrepository.com/artifact/com.itextpdf/itextpdf -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13.2</version>
</dependency>
2. 实现代码
package com.fan.study.common.util;
import com.itextpdf.text.Document;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfWriter;
import java.awt.geom.AffineTransform;
import java.io.FileOutputStream;
public class PdfConvertA4Utils {
/**
* @Param source 源文件
* @Param target 转换后文件
* @Description 将PDF转为A4格式
* @Date: 2021/4/25
**/
private static void convert(String source, String target) {
try {
PdfReader pdfReader = new PdfReader(source);
Document doc = new Document();
PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(target));
doc.open();
PdfContentByte cb = writer.getDirectContent();
for(int i = 1; i <= pdfReader.getNumberOfPages(); i++){
PdfImportedPage page = writer.getImportedPage(pdfReader, i);
float width = page.getWidth();
float height = page.getHeight();
if(height > width) {
//横向
doc.setPageSize(PageSize.A4);
doc.newPage();
//计算比例
float widthScale = getWidthScale(width);
float heightScale = getHeightScale(height);
//addTemplate方法中有6个float类型的参数,是通过二维图像仿射变换得到的
//cb.addTemplate(page, new AffineTransform(widthScale, 0, 0, heightScale,0,0));
//二维图像仿射变换:https://www.cnblogs.com/v2m_/archive/2013/05/09/3070187.html
cb.addTemplate(page, widthScale, 0, 0, heightScale,0,0);
} else {
//纵向
doc.setPageSize(new com.itextpdf.text.Rectangle(PageSize.A4.getHeight(), PageSize.A4.getWidth()));
doc.newPage();
float widthScale = getWidthScale(height);
float heightScale = getHeightScale(width);
cb.addTemplate(page, widthScale, 0, 0, heightScale,0,0);
}
}
doc.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
private static float getWidthScale(float width) {
float scale = PageSize.A4.getWidth() / width;
return scale;
}
private static float getHeightScale(float height) {
float scale = PageSize.A4.getHeight() / height;
return scale;
}
}