我使用OpenOffice创建odt文件,在此文件中创建表单字段,并将odf文件保存为PDF文件。然后使用itext将数据填充到pdf文件中。每个pdf中显示的每个表单字段。但是当我合并pdf文件时,所有表单字段都丢失了。请帮忙。
设置字段代码:
FileOutputStream fos = new FileOutputStream(outpath);
PdfReader reader= new PdfReader(templateinputsream);
PdfStamper stamp = new PdfStamper(reader, fos);
AcroFields form = stamp.getAcroFields();
setField(form, fieldsMap);
private void setField(AcroFields form, Map<String, String> map) {
Iterator<Entry<String, String>> it = map.entrySet().iterator();
while (it.hasNext()) {
Entry<String, String> entry = it.next();
String key = entry.getKey();
String value = entry.getValue();
try {
form.setField(key, value);
} catch (IOException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
}
}
}
合并代码pdf:
private void mergePdf(List<String> files, String savepath) {
try {
List<InputStream> pdfs = new ArrayList<InputStream>();
for (int i = 0; i < files.size(); i++) {
pdfs.add(new FileInputStream(files.get(i)));
}
OutputStream output = new FileOutputStream(savepath);
Document document = new Document(new PdfReader(files.get(0)).getPageSize(1));
concatPDFs(document, pdfs, output);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void concatPDFs(Document document, List<InputStream> streamOfPDFFiles, OutputStream outputStream) {
try {
List<InputStream> pdfs = streamOfPDFFiles;
List<PdfReader> readers = new ArrayList<PdfReader>();
int totalPages = 0;
Iterator<InputStream> iteratorPDFs = pdfs.iterator();
while (iteratorPDFs.hasNext()) {
InputStream pdf = iteratorPDFs.next();
PdfReader pdfReader = new PdfReader(pdf);
readers.add(pdfReader);
totalPages += pdfReader.getNumberOfPages();
}
PdfWriter writer = PdfWriter.getInstance(document, outputStream);
document.open();
PdfContentByte cb = writer.getDirectContent(); // Holds the PDF
PdfImportedPage page;
int pageOfCurrentReaderPDF = 0;
Iterator<PdfReader> iteratorPDFReader = readers.iterator();
while (iteratorPDFReader.hasNext()) {
PdfReader pdfReader = iteratorPDFReader.next();
while (pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) {
document.newPage();
pageOfCurrentReaderPDF++;
page = writer.getImportedPage(pdfReader, pageOfCurrentReaderPDF);
cb.addTemplate(page, 0, 0);
}
pageOfCurrentReaderPDF = 0;
}
outputStream.flush();
document.close();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (document.isOpen())
document.close();
try {
if (outputStream != null)
outputStream.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
答案 0 :(得分:2)
我看到三个可能的问题:
[1]
使用OpenOffice生成的表单存在已知问题:缺少外观! (实际上,有人应该告诉OpenOffice开发人员解决这个问题)。您可以通过添加以下行来解决此问题:
fields.setGenerateAppearances(true);
有关完整示例,请参阅FillDataSheet。
[2]
您犯的错误与"Duplicate questions" versus "RTFM"
中描述的错误相同 正如文档所述,使用PdfWriter
会抛弃所有互动功能。由于您没有压平您的文档,因此这些字段仍然是互动式的,因此通过选择PdfWriter
代替PdfCopy
,您故意扔掉田野......
[3]
当您使用PdfCopy
时,请确保使用最新版本的iText,因为表格的连接仅在最近才实施。请参阅https://stackoverflow.com/a/20659958/1622493以查找问题的几乎完全相同的副本。