我遇到了一个我需要的任务:
起初我尝试过Lowagie库,从2 ...版本转移到itext 然后用Itext 然后转到PDFBox
我在stackoverflow中看到了很多例子,例如点源pdf,目标pdf,要更改的字 复制,粘贴,进行类导入但生成新的pdf而不做任何更改
我正在尝试这些库:
// PDFBox generator
compile 'org.apache.pdfbox:pdfbox:2.0.9'
// Itext generator
compile 'com.itextpdf:itext-pdfa:5.5.10'
compile 'com.itextpdf:itextg:5.5.9'
// Lowagie generator
compile group: 'com.lowagie', name: 'itext', version: '2.1.7'
也许libs正在改变,这会导致某些功能无法正常工作,但是你能为你建议一个有效的解决方案吗?
尝试过这些合作:
private void processPDF(String src, String dest) throws IOException, DocumentException {
PdfReader reader = new PdfReader(src);
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 dd = new String(data, "UTF8")
.replace("text", "replacedText");
stream.setData(dd.getBytes("UTF8"));
}
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
stamper.close();
reader.close();
}
private void processPDF3(String src, String dest) throws InvalidPasswordException, IOException {
Map<String, String> map = new HashMap<>();
map.put("text", "replacedText");
File template = new File(src);
PDDocument document = PDDocument.load(template);
List<PDField> fields = document.getDocumentCatalog().getAcroForm().getFields();
for (PDField field : fields) {
for (Map.Entry<String, String> entry : map.entrySet()) {
if (entry.getKey().equals(field.getFullyQualifiedName())) {
field.setValue(entry.getValue());
field.setReadOnly(true);
}
}
}
File out = new File(dest);
document.save(out);
document.close();
}
也使用了这个:iText Add values to placeholders in PDF cover page dynamically
此变体:PDFBox 2.0 RC3 -- Find and replace text
非常感谢你的帮助