我想合并两个文件的内容,但是在通过PDFBOX或Itext合并时,它仅显示合并文件中的第二个文件内容。两个文件的空闲内容应该在“最终合并”文件中可见。
我曾尝试对Itext和pdfbox进行同样的操作,但我没有成功,即使两个库中的结果相同。
import org.apache.axis.utils.ArrayUtil;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.pdfbox.io.IOUtils;
import org.apache.pdfbox.multipdf.PDFMergerUtility;
import org.apache.pdfbox.pdmodel.PDDocument;
import com.lowagie.text.Document;
import com.lowagie.text.pdf.PdfCopy;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.SequenceInputStream;
public class MergingPdfs {
public static void main(String[] args) throws IOException {
File file1 = new File("D:/PDFMARGE/WELCOME1.pdf");
PDDocument doc1 = PDDocument.load(file1);
File file2 = new File("D:/PDFMARGE/WELCOME2.pdf");
PDDocument doc2 = PDDocument.load(file2);
PDFMergerUtility PDFmerger = new PDFMergerUtility();
PDFmerger.addSource(new ByteArrayInputStream(FileUtils.readFileToByteArray(file1)));
PDFmerger.addSource(new ByteArrayInputStream(FileUtils.readFileToByteArray(file2)));
SequenceInputStream initialStream = new SequenceInputStream(
new ByteArrayInputStream((FileUtils.readFileToByteArray(file2))),
new ByteArrayInputStream(FileUtils.readFileToByteArray(file2)));
byte[] bytesFile1 = FileUtils.readFileToByteArray(file1);
byte[] bytesFile2 = FileUtils.readFileToByteArray(file2);
// byte[] bytes =new byte[bytesFile1.length + bytesFile2.length];
byte[] bytes = ArrayUtils.addAll(bytesFile2, bytesFile1);
System.arraycopy(bytesFile1, 0, bytes, 0, bytesFile1.length);
System.arraycopy(bytesFile2, 0, bytes, bytesFile1.length, bytesFile2.length);
File targetFile = new File("D:/PDFMARGE/merged8.pdf");
OutputStream outStream = new FileOutputStream(targetFile);
for (int i = 0; i < bytes.length; i++) {
outStream.write(bytes[i]);
}
initialStream.close();
System.out.println("Documents merged");
outStream.close();
}
}