package com.test.util.testTableWord; import com.lowagie.text.Document; import com.lowagie.text.pdf.PdfCopy; import com.lowagie.text.pdf.PdfReader; import com.test.exception.ErrorException; import lombok.extern.slf4j.Slf4j;
import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream;
@Slf4j public class TestComparePdf {
public static void main(String[] args) {
String fileName = java.util.UUID.randomUUID().toString().replaceAll("-","") + ".pdf";
List<String> pdfFilenames = new ArrayList<>();
pdfFilenames.add("E:\\app\\ouput.pdf");
pdfFilenames.add("E:\\app\\textWaterMark.pdf");
try {
combinPdf(pdfFilenames,fileName);
} catch (Exception e) {
e.printStackTrace();
}
List<String> srcFiles = new ArrayList<>();
srcFiles.add("E:\\app\\ouput.pdf");
srcFiles.add("E:\\app\\textWaterMark.pdf");
Map<String, String> fileNameMap = new HashMap<>();
fileNameMap.put("E:\\app\\ouput.pdf","ouput");
fileNameMap.put("E:\\app\\textWaterMark.pdf","textWaterMark");
toZip(srcFiles,fileNameMap);
}
/***
* 合并pdf文件
* @param pdfFilenames
* @param filename
* @return
* @throws Exception
*/
public static String combinPdf(List<String> pdfFilenames, String filename) throws Exception {
String targetFilename = "E:\\app\\" + filename;
PdfReader reader = null;
Document doc = new Document();
PdfCopy pdfCopy = new PdfCopy(doc, new FileOutputStream(targetFilename));
int pageCount = 0;
doc.open();
if (pdfFilenames.size()>0) {
for (int i = 0; i < pdfFilenames.size(); ++i) {
reader = new PdfReader(pdfFilenames.get(i));
pageCount = reader.getNumberOfPages();
for (int j = 1; j <= pageCount; ++j) {
pdfCopy.addPage(pdfCopy.getImportedPage(reader, j));
}
}
}
doc.close();
return targetFilename;
}
public static String toZip(List<String> srcFiles, Map<String, String> fileNameMap) throws RuntimeException {
long start = System.currentTimeMillis();
String fileName = "E:\\app\\" + java.util.UUID.randomUUID().toString() + ".zip";
ZipOutputStream zos = null;
try {
FileOutputStream out = new FileOutputStream(fileName);
zos = new ZipOutputStream(out);
for (String srcFile : srcFiles) {
byte[] buf = new byte[4096];
zos.putNextEntry(new ZipEntry(fileNameMap.get(srcFile)+".pdf"));
int len;
FileInputStream in = new FileInputStream(srcFile);
while ((len = in.read(buf)) != -1) {
zos.write(buf, 0, len);
}
in.close();
}
zos.setComment("导出文件");
zos.flush();
zos.closeEntry();
long end = System.currentTimeMillis();
log.info("导出文件打包完成,耗时:" + (end - start) + " ms");
} catch (Exception e) {
throw new ErrorException(400, "打包文件时出错:"+e.toString());
} finally {
if (zos != null) {
try {
zos.close();
} catch (IOException e) {
log.error("打包文件时出错:", e);
}
}
}
return fileName;
}
}
|