我正在努力在合并文档后替换文本。我有一个文档是通过IText从头开始创建的。在第一个pdf中,我可以随时替换任何文本。字符串替换的代码如下。
URL resource = CobAccountOpeningLetterFieldServiceTest.class.getResource(SAMPLE_GENERATED_DOCUMENT);
Date date = CobModelUtils.getUtilDateFromString("Nov 02, 2017");
String region = "en";
String dateFromLocale = getDateFromLocale(region, date);
PdfReader reader = new PdfReader(resource);
PdfDictionary dict = reader.getPageN(1);
PdfObject object = dict.getDirectObject(PdfName.CONTENTS);
if (object instanceof PRStream) {
PRStream stream = (PRStream) object;
byte[] data = PdfReader.getStreamBytes(stream);
String dataString = new String(data, CHARACTER_ENCODING_SET);
System.out.println(dataString);
dataString = dataString.replace(TEMPORARY_DATE_PLACE_HOLDER, dateFromLocale);
stream.setData(dataString.getBytes(CHARACTER_ENCODING_SET));
}
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(RESULT4));
stamper.close();
reader.close();
这个单独工作正常,但是当我合并其中的任何其他文档时,字符串替换将停止处理新PDF。
合并pdf的代码是
private InputStream mergeDocument(List<InputStream> documentToMerge) throws DocumentException, IOException {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
Document document = new Document();
PdfWriter pdfWriter = PdfWriter.getInstance(document, byteArrayOutputStream);
document.open();
PdfContentByte cb = pdfWriter.getDirectContent();
for (InputStream inputStream : documentToMerge) {
PdfReader pdfReader = new PdfReader(inputStream);
PdfReader.unethicalreading = true;
for (int pageOfCurrentReaderPDF = 1; pageOfCurrentReaderPDF <= pdfReader.getNumberOfPages(); pageOfCurrentReaderPDF++) {
Rectangle r = pdfReader.getPageSize(pdfReader.getPageN(pageOfCurrentReaderPDF));
document.setPageSize(r);
document.newPage();
PdfImportedPage page = pdfWriter.getImportedPage(pdfReader, pageOfCurrentReaderPDF);
cb.addTemplate(page, 0, 0);
}
}
byteArrayOutputStream.flush();
document.close();
return new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
}
任何人都早先遇到过这个问题。请指导,谢谢,