使用itextpdf切割、合并pdf以及合并多个图片成为pdf
按页切割PDF文件
import java.util.List;
import java.util.Map;
public interface ISplit {
List<Map<String, String>> split(String filePath) throws Exception;
}
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Log4j2
@Component
public class SplitPdf implements ISplit {
@Value("${filePathPrefix}")
private String filePathPrefix;
@Value("${resources.domain}")
private String resourcesDomain;
@Autowired
public SplitPdf(PptServiceClient pptServiceClient, FileServiceClient fileServiceClient) {
this.pptServiceClient = pptServiceClient;
this.fileServiceClient = fileServiceClient;
}
@SuppressWarnings("unchecked")
@Override
public List<Map<String, String>> split(String filePath) throws Exception {
List<Map<String, String>> mapList = new ArrayList<>();
Document document = null;
PdfCopy copy = null;
PdfReader reader = new PdfReader(new URL(resourcesDomain + filePath));
int n = reader.getNumberOfPages();
for (int i = 1; i <= n; i++) {
String perPagePath = splitPage(reader, filePathPrefix + filePath, i, i);
HashMap<String, String> map = new HashMap<>();
map.put(FileTypeEnum.PDF.getType().toLowerCase(), perPagePath);
mapList.add(map);
}
return mapList;
}
private String splitPage(PdfReader reader, String filePath, Integer from, Integer end) throws DocumentException, IOException {
Document document;
PdfCopy copy;
if (from == 0) {
from = 1;
}
int a = filePath.lastIndexOf("/");
String staticPath = filePath.substring(0, a);
String staticName = filePath.substring(a, filePath.lastIndexOf(".pdf"));
String saveFileName = staticName + "_" + from + ".pdf";
String saveFilePath = staticPath + saveFileName;
document = new Document(reader.getPageSize(1));
copy = new PdfCopy(document, new FileOutputStream(saveFilePath));
document.open();
for (int j = from; j <= end; j++) {
document.newPage();
PdfImportedPage page = copy.getImportedPage(reader, j);
copy.addPage(page);
}
document.close();
return saveFilePath.substring(filePathPrefix.length());
}
}
合并多个PDF文件
import java.util.List;
public interface IMerge {
String merge(List<String> filePathList, String toPath);
}
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfReader;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URL;
import java.util.Calendar;
import java.util.List;
import java.util.UUID;
@Log4j2
@Component
public class MergePdf implements IMerge {
@Value("${filePathPrefix}")
private String filePathPrefix;
@Value("${resources.domain}")
private String resourcesDomain;
@Override
public String merge(List<String> filePathList, String toPath) {
try {
Document document = new Document();
if (toPath == null) {
toPath = "/files/upload" + getFilePathByDate() + "/" + UUID.randomUUID().toString().replace("-", "") + ".pdf";
}
FilePathUtil.mkDirsIfNotExists(filePathPrefix + toPath);
OutputStream bos = new FileOutputStream(filePathPrefix + toPath);
PdfCopy copy = new PdfCopy(document, bos);
document.open();
for (String filePath : filePathList) {
PdfReader reader = new PdfReader(new URL(resourcesDomain + filePath));
copy.addDocument(reader);
copy.freeReader(reader);
reader.close();
}
document.close();
} catch (DocumentException | IOException | ResponseException e) {
log.error("合并PDF文件失败,msg={}", e.getMessage());
return null;
}
return toPath;
}
private String getFilePathByDate() {
Calendar calendar = Calendar.getInstance();
return "/" + calendar.get(Calendar.YEAR) + "/" + (calendar.get(Calendar.MONTH) + 1);
}
}
合并多张图片到PDF文件
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfWriter;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URL;
import java.util.Calendar;
import java.util.List;
import java.util.UUID;
@Log4j2
@Component
public class MergePicture implements IMerge {
@Value("${filePathPrefix}")
private String filePathPrefix;
@Value("${resources.domain}")
private String resourcesDomain;
@Override
public String merge(List<String> filePathList, String toPath) {
try {
Document document = new Document();
if (toPath == null) {
toPath = "/files/upload" + getFilePathByDate() + "/" + UUID.randomUUID().toString().replace("-", "") + ".pdf";
}
FilePathUtil.mkDirsIfNotExists(filePathPrefix + toPath);
OutputStream os = new FileOutputStream(filePathPrefix + toPath);
PdfWriter.getInstance(document, os);
document.open();
for (String filePath : filePathList) {
document.newPage();
BufferedImage img = ImageIO.read(new URL(resourcesDomain + filePath));
int width = img.getWidth();
int height = img.getHeight();
int percent = getPercent2(height, width);
Image image = Image.getInstance(new URL(resourcesDomain + filePath));
image.setAlignment(Image.MIDDLE);
image.scalePercent(percent + 3);
document.add(image);
}
document.close();
} catch (IOException | DocumentException e) {
log.error("合并图片失败,msg={}", e.getMessage());
return null;
}
return toPath;
}
private int getPercent2(float h, float w) {
int p;
float p2;
p2 = 530 / w * 100;
p = Math.round(p2);
return p;
}
private String getFilePathByDate() {
Calendar calendar = Calendar.getInstance();
return "/" + calendar.get(Calendar.YEAR) + "/" + (calendar.get(Calendar.MONTH) + 1);
}
}