maven依赖
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.4.3</version>
</dependency>
前端代码
<template>
<div class="pr" ref="father" >
<div class="bg">
<div class="theme-upload-body">
<div class="theme-upload-drag">
<Upload
multiple="true"
type="drag"
action=""
:before-upload="handleBeforeUpload">
<div style="padding: 45px 0">
<Icon type="ios-folder-outline" size="52" style="color: #3399ff"></Icon>
<p>{{$t('page.verification.dragthefilehere')}}</p>
<p style="color: #acacac;font-size: 12px;text-align: center;">{{$t('page.verification.supportedpdf')}}</p>
</div>
</Upload>
</div>
<div class="theme-upload-data">
<Table :columns="columns" :data="fileData" height="180" size="small"
style="overflow-x: auto"></Table>
</div>
</div>
<Button type="primary" style="margin-left: 20px;margin-top:20px;"
@click="pdfMerge()">
合并文件
</Button>
</div>
<loading :loading="loading"/>
</div>
</template>
<script>
import loading from '@/components/review/loading';
export default {
name: 'pdfMerge',
components: {
loading
},
data () {
return {
pdfFile: [],//上传的pdf文件,
pdfFileList:[],
columns: [
{
title: $t('page.reviewApply.FileName'),
key: 'fileName',
align: 'center',
width: '340',
},
{
title: $t('page.reviewApprove.operate'),
key: 'Operation',
watch: '140',
render: (h, params) => {
return h('div', [
h('Button', {
props: {
type: 'error',
size: 'small'
},
style: {
marginRight: '5px'
},
on: {
click: () => {
this.fileData.splice(params.index, 1);
this.pdfFileList.splice(params.index, 1);
}
}
}, $t('page.reviewApply.removeFile')),
])
}
},
],
fileData: [],
}
},
methods: {
handleBeforeUpload (file) {
let lastNum = file.name.lastIndexOf('.');
let extensionName = file.name.substring(lastNum + 1, file.name.length).trim();
if (extensionName === 'pdf') {
this.pdfFileList.push(file)
this.fileData.push({
fileName: file.name,
});
}else {
this.$Message.error({
content: $t('page.common.pleaseuploadpdf'),
duration: 10,
closable: true
})
}
},
pdfMerge(){
debugger
if(this.pdfFileList.length == 0){
this.$Message.error("请上传pdf文件");
return;
}
let formData = new FormData();
//多个文件上传
for (let i = 0; i < this.pdfFileList.length; i++) {
formData.append("files", this.pdfFileList[i]); // 文件对象
}
this.abHttpUtil.postExcel('/pdm/drawingreview/mergePdf', formData).then((res) => {
if(res.size > 0){
let blob = new Blob([res],{ type: 'application/pdf' })
let downloadElement = document.createElement('a');
let href = window.URL.createObjectURL(blob); // 创建下载的链接
downloadElement.href = href;
downloadElement.download = "合并文件.pdf"; // 下载后文件名
document.body.appendChild(downloadElement);
downloadElement.click(); // 点击下载
document.body.removeChild(downloadElement); // 下载完成移除元素
window.URL.revokeObjectURL(href); // 释放掉blob对象
this.$Message.success("下载成功!");
}else{
this.$Message.error($t('下载失败!'))
}
})
}
},
created: function () {
},
}
</script>
<style lang="less" scoped>
.bg {
width: 100%;
height: 550px;
background-color: white;
float: left;
.theme-upload-body {
display: flex;
align-items: flex-start;
margin-top: 10px;
width: 100%;
}
.theme-upload-drag {
margin-left:20px;
text-align: center;
width: 42%;
}
.theme-upload-data {
width: 40%;
margin-left: 20px;
}
table {
width: 100% !important;
table-layout: auto;
}
}
.td-text {
text-align: right;
}
.bunt {
margin: 0 auto;
width: 300px;
}
</style>
后端代码
@RequestMapping("/mergePdf")
@ApiOperation(value = "合并pdf", httpMethod = "POST")
public ResultMsg mergePdf(@RequestParam("files") MultipartFile[] files, HttpServletResponse response, HttpServletRequest request) throws Exception {
InputStream inputStream = null;
String filePath = "C:\\BusinessFile\\合并文件.pdf";
File file = new File(filePath);
try {
MergePDF.downloadMergePdfFiles(files,filePath);
inputStream = new FileInputStream(file);
response.setContentType("application/pdf");
response.addHeader("Cache-Control", "no-cache, no-store, must-revalidate");
response.addHeader("charset", "utf-8");
response.addHeader("Pragma", "no-cache");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("合并文件.pdf", "utf-8"));
// 循环取出流中的数据
byte[] b = new byte[1024];
int len;
try {
while ((len = inputStream.read(b)) > 0) {
response.getOutputStream().write(b, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
inputStream.close();
file.delete();
}
}catch (Exception e){
e.printStackTrace();
}
return getSuccessResult();
}
package com.nssol_sh.bizbooster.tmec.pdm.utils;
import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import org.apache.commons.io.FileUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
public class MergePDF {
public static void main(String[] args) {
String[] files = {"H:\\pdf\\part2.pdf", "H:\\pdf\\part3.pdf"};
String savePath = "H:\\pdf\\final.pdf";
mergePdfFiles(files,savePath);
}
public static boolean mergePdfFiles(String[] files, String newFile) {
if(files.length == 1) {
File file = new File(files[0]);
File fileOut = new File(newFile);
try {
FileUtils.copyFile(file,fileOut);
com.nssol_sh.bizbooster.tmec.pdm.utils.FileUtils.removeFile(files[0]);
} catch (IOException e) {
e.printStackTrace();
}
} else {
boolean retValue = false;
Document document = null;
FileOutputStream fileOutputStream = null;
PdfReader pdfReader = null;
try {
pdfReader = new PdfReader(files[0]);
document = new Document(pdfReader.getPageSize(1));
fileOutputStream = new FileOutputStream(newFile);
PdfCopy copy = new PdfCopy(document,fileOutputStream);
document.open();
for (int i = 0; i < files.length; i++) {
PdfReader reader = new PdfReader(files[i]);
int n = reader.getNumberOfPages();
for (int j = 1; j <= n; j++) {
document.newPage();
PdfImportedPage page = copy.getImportedPage(reader, j);
copy.addPage(page);
}
reader.close();
}
retValue = true;
} catch (Exception e) {
System.out.println(e);
try {
pdfReader.close();
document.close();
fileOutputStream.close();
} catch (IOException ioException) {
ioException.printStackTrace();
}
} finally {
System.out.println("执行结束");
document.close();
pdfReader.close();
}
for (String file : files) {
File file1 = new File(file);
if (file1.exists()){
boolean delete = file1.delete();
System.out.println(delete);
}
}
}
return true;
}
/**
* 合并pdf文件
* @param files 获取上传的文件
* @param newFile 下载的文件路径
*/
public static void downloadMergePdfFiles(MultipartFile[] files,String newFile) {
Document document = null;
FileOutputStream fileOutputStream = null;
PdfReader pdfReader = null;
try {
pdfReader = new PdfReader(files[0].getInputStream());
document = new Document(pdfReader.getPageSize(1));
fileOutputStream = new FileOutputStream(newFile);
PdfCopy copy = new PdfCopy(document,fileOutputStream);
document.open();
for (MultipartFile file : files) {
// 读取源文件
PdfReader reader = new PdfReader(file.getInputStream());
int n = reader.getNumberOfPages();
for (int i = 1; i <= n; i++) {
document.newPage();
PdfImportedPage page = copy.getImportedPage(reader, i);
copy.addPage(page);
}
reader.close();
}
} catch (Exception e) {
try {
pdfReader.close();
document.close();
fileOutputStream.close();
} catch (IOException ioException) {
ioException.printStackTrace();
}
} finally {
System.out.println("执行结束");
document.close();
pdfReader.close();
}
}
}
效果图