如何在PDF中创建水印

时间:2014-08-18 08:22:46

标签: java pdf pdf-generation itext

我有一个程序,我正在为某个组织生成收据。我需要在文档中添加一个waterark作为某种安全性。我在下面添加我的代码。我的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());
    }
    }
}

2 个答案:

答案 0 :(得分:0)

在声明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----------

答案 1 :(得分:0)

我已经使用以下生成水印的代码

解决了这个问题
    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());