Несколько водяных масок с использованием iText PDF

Я использую iTextPdf для создания текстовых водяных знаков на странице. В настоящее время водяной знак отображается в центре страницы, но я хотел бы добавить несколько водяных знаков (45 градусов) по всей странице. Если водяной знак маленький, мне нужно два или три водяных знака на одной строке.

Вот код

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PatternColor;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPatternPainter;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.RandomAccessFileOrArray;
public class TestWaterMarkPdf {
  public static void main(String[] args) throws IOException, DocumentException {
      waterMarkFile(new File("2851048.pdf"),new File("test2.pdf"));
  }
  public static void waterMarkFile(File pdfFile, File target) {
        ByteArrayOutputStream bos   = null;            
        try {      
               String outputFileLoc     = pdfFile.getAbsolutePath();
              // bos                      = new ByteArrayOutputStream();
               PdfReader reader         = new PdfReader(new RandomAccessFileOrArray(outputFileLoc),null);
               int number_of_pages      = reader.getNumberOfPages();
               FileOutputStream os      = new FileOutputStream(target);
               PdfStamper stamper       = new PdfStamper(reader, os);
               Rectangle pageSize           = reader.getPageSizeWithRotation(1);
               PdfPatternPainter painter    = stamper.getOverContent(1).createPattern(pageSize.getWidth(), pageSize.getHeight());

               for (int i = 1; i <= number_of_pages; i++) {  
                   PdfContentByte overContent           = stamper.getOverContent(i);  
                   watermarkPage(overContent, painter,pageSize);
                   overContent.setColorFill(new PatternColor(painter));
                   overContent.rectangle(pageSize.getLeft(), pageSize.getBottom(), pageSize.getWidth(), pageSize.getHeight());
                   overContent.fill(); 
               }
               stamper.close();
               reader.close(); 
               os.close();

        } catch (Exception e) {

        }
}  

    static void watermarkPage(PdfContentByte overContent,PdfPatternPainter painter,Rectangle pageSize) throws IOException, DocumentException {
        final float WATERMARK_PAGE_ANGLE = 45;      
        BaseFont font = BaseFont.createFont(BaseFont.HELVETICA_BOLD, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);

        painter.setColorStroke(new BaseColor(192, 192, 192));
        painter.setLineWidth(0.85f);
        painter.setLineDash(0.4f, 0.4f, 0.2f);

        painter.beginText();
        painter.setTextRenderingMode(PdfPatternPainter.TEXT_RENDER_MODE_STROKE);
        painter.setFontAndSize(font, 30);
        painter.showTextAlignedKerned(Element.ALIGN_CENTER,
                "Confidential",  pageSize.getWidth() / 2, pageSize.getHeight() / 2,
                WATERMARK_PAGE_ANGLE);    
          painter.endText();
    }
}

person user3718208    schedule 08.06.2014    source источник


Ответы (1)


Немного математики может иметь большое значение, используйте базовый триггер для вычисления x и y. изменения, которые вам понадобятся для данного угла, и повторите ширину и высоту страницы, рисуя текст.

static void watermarkPage(PdfContentByte overContent,PdfPatternPainter painter,Rectangle pageSize) throws IOException, DocumentException {
    final float WATERMARK_PAGE_ANGLE = 45;      
    BaseFont font = BaseFont.createFont(BaseFont.HELVETICA_BOLD, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);

    painter.setColorStroke(new Color(192, 192, 192));
    painter.setLineWidth(0.85f);
    painter.setLineDash(0.4f, 0.4f, 0.2f);

    painter.beginText();
    painter.setTextRenderingMode(PdfPatternPainter.TEXT_RENDER_MODE_STROKE);

    float fontSize = 30f;
    painter.setFontAndSize(font, fontSize);
    String text = "Confidential";


    // get our strings width and height to use for the loop
    float width = painter.getEffectiveStringWidth(text, false);
    float height = font.getAscentPoint(text, fontSize) + font.getDescentPoint(text, fontSize);

    // get the x and y factors we need for the given angle
    float xFactor = (float) Math.cos(Math.toRadians(WATERMARK_PAGE_ANGLE));
    float yFactor = (float) Math.sin(Math.toRadians(WATERMARK_PAGE_ANGLE));
    // for our entire width and height of our page place a watermark
    for(float  x=0; x<pageSize.getWidth();x+=width*xFactor+height*yFactor) {
        for(float y=-60f*yFactor; y<pageSize.getHeight();y+=width*yFactor+height*xFactor) {

            painter.showTextAlignedKerned(Element.ALIGN_CENTER,
                    text,  x, y,
                    WATERMARK_PAGE_ANGLE);    

        }
    }
    painter.endText();
}
person ug_    schedule 08.06.2014