打开并保存为相同的PDF文件名

时间:2018-01-09 19:05:14

标签: java pdf itext

我需要在PDF文件中附加水印, 但我想避免创建一个新文件。 除非我给输出流指定了不同的名称,否则以下代码将不起作用。 如何调整语法和/或顺序以获得我追求的结果?

public class AppendHistoricalWatermark {

public AppendHistoricalWatermark(SmbFile smbfile){

    System.out.println("AppendHistoricalWatermark: " + smbfile.getPath());

    try{
        PdfDocument pdfDoc = new PdfDocument(new PdfReader(smbfile.getInputStream()), new PdfWriter(smbfile.getOutputStream()));
        Document document = new Document(pdfDoc);
        Rectangle pageSize;
        PdfCanvas canvas;
        int n = pdfDoc.getNumberOfPages();
        System.out.println("AppendHistoricalWatermark: NumberOfPages: " + n);

        for (int i = 1; i <= n; i++) {
            PdfPage page = pdfDoc.getPage(i);
            pageSize = page.getPageSize();
            canvas = new PdfCanvas(page);

            Paragraph p = new Paragraph("HISTORICAL").setFontSize(60);
            canvas.saveState();
            PdfExtGState gs1 = new PdfExtGState().setFillOpacity(0.2f);
            canvas.setExtGState(gs1);
            document.showTextAligned(p, pageSize.getWidth() / 2, pageSize.getHeight() / 2, pdfDoc.getPageNumber(page), 
                TextAlignment.CENTER, VerticalAlignment.MIDDLE, 45);
            canvas.restoreState();


        }
        pdfDoc.close();



    }
    catch(Exception e){
        System.out.println("AppendHistoricalWatermark: " + e);
        e.printStackTrace();
    }
}

}

0 个答案:

没有答案