Java 如何在PDF中创建水印

Java 如何在PDF中创建水印,java,pdf,pdf-generation,itext,Java,Pdf,Pdf Generation,Itext,我有一个程序,我正在为某个组织生成一张收据。为了安全起见,我需要在文件中添加一个水柜。我正在下面添加我的代码。我的PDF已经生成,但如何添加水印 /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.example; import com.lowagie.text.*; import com.lowagie.text.pdf

我有一个程序,我正在为某个组织生成一张收据。为了安全起见,我需要在文件中添加一个水柜。我正在下面添加我的代码。我的PDF已经生成,但如何添加水印

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.example;

import com.lowagie.text.*;
import com.lowagie.text.pdf.*;
import java.awt.Color;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

/**
 *
 * @author Chandan
 */
public class MoneryRecipt {

   // Document m_PdfDocument;


    public static void main(String[] args) throws DocumentException, FileNotFoundException
    {
              Document m_PdfDocument = new Document(PageSize.LETTER, 5, 5, 5, 5);

   try
   {
       DocWriter m_DocWriter;
   // PdfWriter m_PdfWriter = null;

          PdfWriter writer =  PdfWriter.getInstance(m_PdfDocument, new FileOutputStream("E:/aa.pdf"));

      Image logo=Image.getInstance("F:/gmc_report.jpg");
      m_PdfDocument.open();
      Image background = Image.getInstance(logo);
      background.setAbsolutePosition(200, 400);
     // Phrase watermarkdd = new Phrase("Chandan Sarma", new Font(FontFactory.getFont(FontFactory.HELVETICA, 20,Font.NORMAL,new Color(240,240,240))));
      PdfContentByte canvas = writer.getDirectContentUnder();
      PdfContentByte addWaterMark;
      addWaterMark=writer.getDirectContentUnder();
      addWaterMark.addImage(logo);


        PdfPTable maintable = new PdfPTable(2);
        PdfPCell spece = new PdfPCell();
        spece.setBorder(0);
        spece.setColspan(2);
        spece.setFixedHeight(20f);
        spece.setSpaceCharRatio(20f);
        maintable.addCell(spece);

        Image logo=Image.getInstance("D:/logo_gmcmanin.png");


        Paragraph ph = new Paragraph();
        ph.add(new Chunk(logo, 0, 0));
        ph.add(new Chunk("\n\nGuwahati Municipal Corporation", FontFactory.getFont(FontFactory.TIMES_ROMAN, 10, Font.BOLDITALIC)));
        ph.add(new Chunk("\n\nMoney recipt", FontFactory.getFont(FontFactory.TIMES_ROMAN, 10, Font.BOLD)));

        PdfPCell heading = new PdfPCell(ph);
  //      heading.setBorder(1);
        heading.setColspan(2);
        heading.setHorizontalAlignment(Element.ALIGN_CENTER);
        heading.setVerticalAlignment(Element.ALIGN_CENTER);
        maintable.addCell(heading);

        Paragraph ph2 = new Paragraph();
        ph2.add(new Chunk("\nPayment Receipt / Acknowledgment for Property Tax Bill of the ", FontFactory.getFont(FontFactory.TIMES_ROMAN, 10, Font.BOLDITALIC)));
        ph2.add(new Chunk("\n\nFinancial Year 2014-15", FontFactory.getFont(FontFactory.TIMES_ROMAN, 10, Font.BOLD)));

        PdfPCell reciptHeading = new PdfPCell(ph2);
  //      heading.setBorder(1);
        reciptHeading.setColspan(2);
        reciptHeading.setHorizontalAlignment(Element.ALIGN_CENTER);
        reciptHeading.setVerticalAlignment(Element.ALIGN_CENTER);
        maintable.addCell(reciptHeading);

        Paragraph ph3 = new Paragraph();
        ph3.add(new Chunk("Receipt No  ", FontFactory.getFont(FontFactory.TIMES_ROMAN, 8, Font.NORMAL)));
        ph3.add(new Chunk(" 2014-15", FontFactory.getFont(FontFactory.TIMES_ROMAN, 8, Font.NORMAL)));

        PdfPCell reciptCell=new PdfPCell(ph3);
        //reciptCell.setBorder(0);
        //reciptCell.setBorderWidthLeft(1);
        reciptCell.setBorderWidthBottom(0);
        reciptCell.setBorderWidthTop(0);
        reciptCell.setBorderWidthRight(0);
        reciptCell.setColspan(1);
        reciptCell.setHorizontalAlignment(Element.ALIGN_CENTER);
        reciptCell.setVerticalAlignment(Element.ALIGN_CENTER);
        maintable.addCell(reciptCell);

        Paragraph ph4 = new Paragraph();
        ph4.add(new Chunk("Date ", FontFactory.getFont(FontFactory.TIMES_ROMAN, 8, Font.NORMAL)));
        ph4.add(new Chunk("2014-15", FontFactory.getFont(FontFactory.TIMES_ROMAN, 8, Font.NORMAL)));

        PdfPCell dateCell=new PdfPCell(ph4);
        dateCell.setFixedHeight(20);
        //dateCell.setBorder(0);
        dateCell.setBorderWidthLeft(0);
        dateCell.setColspan(1);
        dateCell.setBorderWidthTop(0);
        dateCell.setBorderWidthBottom(0);
        dateCell.setHorizontalAlignment(Element.ALIGN_CENTER);
        dateCell.setVerticalAlignment(Element.ALIGN_CENTER);
        maintable.addCell(dateCell);

         PdfPCell details = new PdfPCell();
         //details.setBorder(0);
         details.setColspan(2);


        PdfPTable detailsTable = new PdfPTable(2);
        detailsTable.setWidthPercentage(65);

        PdfPCell ownerCell=new PdfPCell(new Phrase("Owner’s Name  ", FontFactory.getFont(FontFactory.TIMES_ROMAN, 8, Font.NORMAL)));
        ownerCell.setHorizontalAlignment(Element.ALIGN_LEFT);
        detailsTable.addCell(ownerCell);

        PdfPCell ownernameCell=new PdfPCell(new Phrase("Chandan Sarma ", FontFactory.getFont(FontFactory.TIMES_ROMAN, 8, Font.NORMAL)));
        ownernameCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        detailsTable.addCell(ownernameCell);

        PdfPCell assementIdOldCell=new PdfPCell(new Phrase("Assessment id (old) ", FontFactory.getFont(FontFactory.TIMES_ROMAN, 8, Font.NORMAL)));
        assementIdOldCell.setHorizontalAlignment(Element.ALIGN_LEFT);
        detailsTable.addCell(assementIdOldCell);


        PdfPCell assementIdValueCell=new PdfPCell(new Phrase("27-05-7859 ", FontFactory.getFont(FontFactory.TIMES_ROMAN, 8, Font.NORMAL)));
        assementIdValueCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        detailsTable.addCell(assementIdValueCell);


        PdfPCell assementIdNewCell=new PdfPCell(new Phrase("Assessment id (New) ", FontFactory.getFont(FontFactory.TIMES_ROMAN, 8, Font.NORMAL)));
        assementIdOldCell.setHorizontalAlignment(Element.ALIGN_LEFT);
        detailsTable.addCell(assementIdOldCell);

        PdfPCell assementIdNewValueCell=new PdfPCell(new Phrase("225642 ", FontFactory.getFont(FontFactory.TIMES_ROMAN, 8, Font.NORMAL)));
        assementIdNewValueCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        detailsTable.addCell(assementIdNewValueCell);

        details.setBorderWidthTop(0);
        details.setBorderWidthBottom(0);
        details.addElement(detailsTable);
        maintable.addCell(details);

        Paragraph ph6=new Paragraph();
        ph6.add(new Chunk("HOUSEHOLD WASTE COLLECTION ", FontFactory.getFont(FontFactory.TIMES_ROMAN, 8, Font.BOLDITALIC,Color.RED)));
        ph6.add(new Chunk("\n\nWard-wise contact number of NGOs for collecting household waste from your doorstep:- ", FontFactory.getFont(FontFactory.TIMES_ROMAN, 6)));
        ph6.add(new Chunk("\n\nWard No. 1-   9957047867       Ward No. 17- 9864623744", FontFactory.getFont(FontFactory.TIMES_ROMAN, 6)));
        ph6.add(new Chunk("\n\nWard No. 1-   9957047867       Ward No. 17- 9864623744", FontFactory.getFont(FontFactory.TIMES_ROMAN, 6)));
        ph6.add(new Chunk("\n\nWard No. 1-   9957047867       Ward No. 17- 9864623744", FontFactory.getFont(FontFactory.TIMES_ROMAN, 6)));
        ph6.add(new Chunk("\n\nWard No. 1-   9957047867       Ward No. 17- 9864623744", FontFactory.getFont(FontFactory.TIMES_ROMAN, 6)));
        ph6.add(new Chunk("\n\nWard No. 1-   9957047867       Ward No. 17- 9864623744", FontFactory.getFont(FontFactory.TIMES_ROMAN, 6)));
        PdfPCell wasteCollectionHeader=new PdfPCell(ph6);
        wasteCollectionHeader.setColspan(1);
        wasteCollectionHeader.setHorizontalAlignment(Element.ALIGN_CENTER);
        maintable.addCell(wasteCollectionHeader);

        Paragraph ph7=new Paragraph();
        ph7.add(new Chunk("PROPERTY TAX RELATED GRIEVANCE REDRESSAL MECHANISM  ", FontFactory.getFont(FontFactory.TIMES_ROMAN, 8, Font.BOLDITALIC,Color.RED)));
        ph7.add(new Chunk("\n\nFor billing or any service grievance, please approach (during office hours) ", FontFactory.getFont(FontFactory.TIMES_ROMAN, 6)));
        ph7.add(new Chunk("\n\n  •Deputy Commissioner, East Zone, GMC, Bhaya Mama Path, RG Baruah Road, Mobile No: 07399092259 ", FontFactory.getFont(FontFactory.TIMES_ROMAN, 6)));
        ph7.add(new Chunk("\n\n  •Deputy Commissioner, East Zone, GMC, Bhaya Mama Path, RG Baruah Road, Mobile No: 07399092259 ", FontFactory.getFont(FontFactory.TIMES_ROMAN, 6)));
        ph7.add(new Chunk("\n\n  •Deputy Commissioner, East Zone, GMC, Bhaya Mama Path, RG Baruah Road, Mobile No: 07399092259 ", FontFactory.getFont(FontFactory.TIMES_ROMAN, 6)));
        ph7.add(new Chunk("\n\n  •Deputy Commissioner, East Zone, GMC, Bhaya Mama Path, RG Baruah Road, Mobile No: 07399092259 ", FontFactory.getFont(FontFactory.TIMES_ROMAN, 6)));
        ph7.add(new Chunk("\n\n  •Deputy Commissioner, East Zone, GMC, Bhaya Mama Path, RG Baruah Road, Mobile No: 07399092259 ", FontFactory.getFont(FontFactory.TIMES_ROMAN, 6)));

        PdfPCell propertyTexRelatedHeader=new PdfPCell(ph7);
        propertyTexRelatedHeader.setColspan(1);
        propertyTexRelatedHeader.setHorizontalAlignment(Element.ALIGN_CENTER);
        maintable.addCell(propertyTexRelatedHeader);






        m_PdfDocument.add(maintable);
        m_PdfDocument.newPage();
        m_PdfDocument.setPageSize(m_PdfDocument.getPageSize());


        m_PdfDocument.close();

    }

    catch(Exception e)
    {
       System.out.println("Exception is"+e.toString());
    }
    }
}

声明Pdf writer时添加以下代码行

PdfWriter writer =  PdfWriter.getInstance(m_PdfDocument, new FileOutputStream("D:/aa.pdf"));

m_PdfDocument.open();
Phrase watermarkdd = new Phrase("Water mark name-", new Font(FontFactory.getFont(FontFactory.HELVETICA, 20,Font.NORMAL,new Color(240,240,240))));
PdfContentByte canvas = writer.getDirectContentUnder();
ColumnText.showTextAligned(canvas, Element.ALIGN_CENTER, watermarkdd, 298, 421, 45);

----Your remaining code goes here----------

我已经用下面的代码解决了这个问题,这些代码已经生成了水印

    class PDFBackground extends PdfPageEventHelper {

    @Override
   public  void onEndPage(PdfWriter writer, Document document) {
                try {
                    Image background = Image.getInstance("F:/gmc_report.jpg");
                    background.setAbsolutePosition(250, 500);
                    // This scales the image to the page,
                    // use the image's width & height if you don't want to scale.
                    float width = document.getPageSize().getWidth();
                    float height = document.getPageSize().getHeight();
                    writer.getDirectContentUnder().addImage(background, false);
                } catch (DocumentException ex) {
                    Logger.getLogger(MoneryRecipt.class.getName()).log(Level.SEVERE, null, ex);
                }  catch (MalformedURLException ex) {
                    Logger.getLogger(MoneryRecipt.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IOException ex) {
                    Logger.getLogger(MoneryRecipt.class.getName()).log(Level.SEVERE, null, ex);
                }
    }
}

并通过以下方式将图像写入pdf中:

    PdfWriter writer =  PdfWriter.getInstance(m_PdfDocument, new FileOutputStream("E:/aa.pdf"));
     writer.setPageEvent(new PDFBackground());

我在你的密码里看到了我的名字。这意味着您使用的版本不再受支持。由于您选择使用过时的版本,因此给出的任何答案都可能不起作用。我在您的代码中看到了
DocWriter
。这个类没有在任何官方示例中使用。对我来说,你为什么要使用它是一个谜,这清楚地表明你没有阅读任何官方文件。@Bruno Lowagie你是对的。我没有使用DocWriter。我忘了把它取下来。事实上,这是一个旧版本的itext,我正在处理一个旧项目,他们只使用旧版本,我不想更新它。水印只是一个半透明的文本,覆盖在所有其他内容之上的页面上。如文件所述,您在
onedpage()中创建的PDF的每个页面上都添加了一个水印
页面事件的方法。@Bruno Lowagie我只能为一个人生成一个页面。你可以修改我的代码,它支持水印。提前谢谢实际上我不明白。你能用我的代码详细说明一下吗?这样我就可以理解了。这只会在第一页上添加水印,而不是在所有后续页面上,因此答案不完整。Lowagie!你没查过吗?。如果您多次打开pdf文档,则必须始终声明它。所以它会出现在所有页面上。Chandan,你想在pdf中添加图像吗?code Monkey是的。我也尝试过,但它给了我setAbsolute position的例外