以下是创建pdf文件的代码段,其中页面可以在生成的文件中旋转。这适用于大多数pdf文件。但是,在对其应用进一步旋转时,页面的一个特定pdf文件已经旋转了180。 90度并保存文件会导致文件损坏。事实上,即使您不旋转文件并使用iText将文件写入另一个文件,生成的PDF文件也会损坏,并在Adobe Reader中打开时显示内存不足异常。
为什么会这样?我在文件中遗漏了某种压缩。
private String createPdfFileWithoutForms(final EditStateData[] editStateData, final String directory)
throws EditingException {
Long startTime = System.currentTimeMillis();
File pdfFileToReturn = new File(directory + File.separator + UidGenerator.generate() + ".pdf");
com.lowagie.text.Document document = null;
FileOutputStream outputStream = null;
PdfCopy pdfCopy = null;
PdfReader reader = null;
PdfDictionary pageDict = null;
int rotationAngle = 0;
Map<Integer, Integer> rotationQuadrants = null;
try {
document = new com.lowagie.text.Document();
outputStream = new FileOutputStream(pdfFileToReturn);
pdfCopy = new PdfCopy(document, outputStream);
pdfCopy.setFullCompression();
pdfCopy.setCompressionLevel(9);
document.open();
for (EditStateData state : editStateData) {
try {
reader = new PdfReader(state.getFileName());
reader.selectPages(state.getPages());
rotationQuadrants = state.getRotationQuadrants();
for (int i = 1; i <= reader.getNumberOfPages(); i++) {
// Rotation quadrant key is the source page number
if (rotationQuadrants.containsKey(state.getPages().get(i - 1))) {
rotationAngle = reader.getPageRotation(i);
pageDict = reader.getPageN(i);
pageDict.put(PdfName.ROTATE,
new PdfNumber((rotationAngle
+ rotationQuadrants.get(state.getPages().get(i - 1))) % 360));
}
document.setPageSize(reader.getPageSizeWithRotation(i));
document.newPage();
// import the page from source pdf
PdfImportedPage page = pdfCopy.getImportedPage(reader, i);
// add the page to the destination pdf
pdfCopy.addPage(page);
}
} catch (final IOException e) {
LOGGER.error(e.getMessage(), e);
throw new EditingException(e.getMessage(), e);
} finally {
if (reader != null) {
reader.close();
}
}
}
} catch (final Exception e) {
LOGGER.error(e.getMessage(), e);
throw new EditingException(e.getMessage(), e);
} finally {
if (document != null) {
document.close();
}
if (pdfCopy != null) {
pdfCopy.close();
}
IoUtils.closeQuietly(outputStream);
}
LOGGER.debug("Combining " + editStateData.length + " pdf files took "
+ ((System.currentTimeMillis() - startTime) / 1000) + " msecs");
return pdfFileToReturn.getAbsolutePath();
}