我正在使用PDF文件。我需要在現有的pdf文件上添加水印。這就是爲什麼,我寫了下面的代碼。當我使用FileOutputStream時,它完美地工作,但我需要使用ByteArrayOutputStream,因爲我的數據來自數據庫,我需要將它保存爲字節數組。問題從這裏開始。當我使用PdfStamper的ByteArrayOutputStream getOvercontent方法返回null時。我該如何處理?提前致謝。 當使用ByteArrayOutputStream時,Itext PdfStamper getOverContent返回null
byte[] bytes = getAsByteArray();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(bytes.length);
PdfReader reader = new PdfReader(bytes);
int numberOfPages= reader.getNumberOfPages();
outputStream.write(bytes, 0, bytes.length);
PdfStamper stamper = new PdfStamper(reader, outputStream);
Font font = font(Font.NORMAL, 135, Color.RED);
for (int i = 0; i < numberOfPages; i++) {
//over Content is null
PdfContentByte over = stamper.getOverContent(i);
Phrase p = new Phrase("WATERMARK", font);
PdfGState gs = new PdfGState();
gs.setFillOpacity(0.5f);
over.setGState(gs);
ColumnText.showTextAligned(over, Element.ALIGN_CENTER, p, 330, 450, 45);
over.saveState();
}
而舊版本的代碼是這樣的。
byte[] bytes = FileUtils.readFileToByteArray(new File("myPdf.pdf"));
PdfReader reader = new PdfReader(bytes);
int numberOfPages= reader.getNumberOfPages();
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("MyPdfOut.pdf"));
Font f = font(Font.NORMAL, 135, Color.RED);
for (int i = 1; i <= numberOfPages; i++) {
PdfContentByte over = stamper.getOverContent(i);
Phrase p = new Phrase("WATERMARK", f);
PdfGState gs = new PdfGState();
gs.setFillOpacity(0.5f);
over.setGState(gs);
ColumnText.showTextAligned(over, Element.ALIGN_CENTER, p, 330, 450, 45);
over.saveState();
}
感謝您的幫助。這是非常痛苦的5個小時。 –