【问题标题】:add itext WaterMark to android java pdf将itext WaterMark添加到android java pdf
【发布时间】:2022-07-31 01:47:54
【问题描述】:

我需要在我的 pdf android java pdf 文件中添加 itext 水印 我用于创建 pdf 文件的示例当前代码:

   File docsFolder = new File(Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_DOWNLOADS), "osary/estmara");
         String currentDate = new SimpleDateFormat("dd-MM-yyyy_hh_mm_aaa", Locale.getDefault()).format(new Date());
            String pdfname = myEstmaraa.getTalabId() + "_" + currentDate + ".pdf";
            pdfFile = new File(docsFolder, pdfname);
            OutputStream output = new FileOutputStream(pdfFile);
            Document document = new Document(PageSize.A4);
            document.setMargins(5, 5, 5, 5);
            PdfWriter PdfWriters = PdfWriter.getInstance(document, output);
            PdfWriters.createXmpMetadata();
            PdfWriters.setTagged();
            document.open();
            //todo 2 preparing Header and directions and margin row 0
            PdfPTable tableForRowZero = new PdfPTable(new float[]{1});
            tableForRowZero.setSpacingBefore(5);
            tableForRowZero.setRunDirection(PdfWriter.RUN_DIRECTION_RTL);
            tableForRowZero.getDefaultCell().setFixedHeight(34);
            tableForRowZero.setTotalWidth(PageSize.A4.getWidth());
            tableForRowZero.setWidthPercentage(100);
            tableForRowZero.setHeaderRows(0);
            tableForRowZero.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);
            cellss = new PdfPCell(new Phrase("رقم الاستمارة", FONT2));
            cellss.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellss.setVerticalAlignment(Element.ALIGN_CENTER);
            cellss.setBackgroundColor(BaseColor.GRAY);
            tableForRowZero.addCell(cellss);
            tableForRowZero.setHeaderRows(0);
            cellss = new PdfPCell(new Phrase(String.valueOf(myEstmaraa.getTalabId()), FONT2));
            cellss.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellss.setVerticalAlignment(Element.ALIGN_CENTER);
            tableForRowZero.addCell(cellss);
            document.add(tableForRowZero);
            document.close();

我已经尝试过这段代码,但它适用于桌面 java: enter link description here

我面临的问题是这一行:

        PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(dest));

当我将其更改为 android 时遇到问题,我尝试过:

        com.itextpdf.kernel.pdf.PdfDocument pdfDoc = new com.itextpdf.kernel.pdf.PdfDocument(new PdfReader(pdfFile.getPath()),new PdfWriter(pdfFile.getPath()));

它给了我这个提示:

无法解析构造函数'PdfWriter(java.lang.String)'

我尝试制作水印的代码:

   com.itextpdf.kernel.pdf.PdfDocument pdfDoc = new com.itextpdf.kernel.pdf.PdfDocument(new PdfReader(pdfFile.getPath()),new PdfWriter(pdfFile.getPath()));
           PdfCanvas under = new PdfCanvas(pdfDoc.getFirstPage().newContentStreamBefore(), new PdfResources(), pdfDoc);
            PdfFont font = PdfFontFactory.createFont(FontProgramFactory.createFont(StandardFonts.HELVETICA));
            com.itextpdf.layout.element.Paragraph paragraph2 = new com.itextpdf.layout.element.Paragraph("This watermark is added UNDER the existing content")
                    .setFont(font)
          .setFontSize(15);

            Canvas canvasWatermark1 = new Canvas(under, pdfDoc.getDefaultPageSize())
                    .showTextAligned(paragraph2, 297, 550, 1, TextAlignment.CENTER, VerticalAlignment.TOP, 0);
            canvasWatermark1.close();
            PdfCanvas over = new PdfCanvas(pdfDoc.getFirstPage());
            over.setFillColor(ColorConstants.BLACK);
            paragraph2 = new com.itextpdf.layout.element.Paragraph("This watermark is added ON TOP OF the existing content")
                    .setFont(font)
                    .setFontSize(15);

            Canvas canvasWatermark2 = new Canvas(over, pdfDoc.getDefaultPageSize())
                    .showTextAligned(paragraph2, 297, 500, 1, TextAlignment.CENTER, VerticalAlignment.TOP, 0);
            canvasWatermark2.close();
            paragraph2 = new com.itextpdf.layout.element.Paragraph("This TRANSPARENT watermark is added ON TOP OF the existing content")
                    .setFont(font)
                    .setFontSize(15);
            over.saveState();

            // Creating a dictionary that maps resource names to graphics state parameter dictionaries
            PdfExtGState gs1 = new PdfExtGState();
            gs1.setFillOpacity(0.5f);
            over.setExtGState(gs1);
            Canvas canvasWatermark3 = new Canvas(over, pdfDoc.getDefaultPageSize())
                    .showTextAligned(paragraph2, 297, 450, 1, TextAlignment.CENTER, VerticalAlignment.TOP, 0);
            canvasWatermark3.close();
            over.restoreState();

我也尝试添加 png 图像并设置其不透明度,但它覆盖了内容

      try {


                com.itextpdf.text.Image image1_emp_osary = null;
                Drawable d_emp_osary = getResources().getDrawable(R.drawable.ketm_estmara);
                BitmapDrawable bitDw_emp_osary = ((BitmapDrawable) d_emp_osary);
                Bitmap bmp_emp_osary = bitDw_emp_osary.getBitmap();
                ByteArrayOutputStream stream_emp_osary = new ByteArrayOutputStream();
                bmp_emp_osary.compress(Bitmap.CompressFormat.PNG, 100, stream_emp_osary);
                image1_emp_osary = com.itextpdf.text.Image.getInstance(stream_emp_osary.toByteArray());
                image1_emp_osary.scaleToFit(200, 200);
                image1_emp_osary.setAlignment(Element.ALIGN_BOTTOM);
                image1_emp_osary.setSpacingBefore(200);
                image1_emp_osary.setTransparency(new int[]{5, 5});
                document.add(new Chunk(image1_emp_osary, 0, 200));
                PdfContentByte canvas = PdfWriters.getDirectContentUnder();
                PdfGState state = new PdfGState();
                state.setFillOpacity(0.6f);
                canvas.setGState(state);
                canvas.addImage(image1_emp_osary);
                canvas.restoreState();
            } catch (Exception e) {
                e.printStackTrace();
            }

【问题讨论】:

  • 你使用哪个版本的itext?
  • 确实,您的一些代码片段适用于 iText 5(或更早版本),一些适用于 iText 7。您(想要)使用哪个版本?
  • @mkl 任何事情都可以完成任务,你能帮帮我吗?

标签: java android itext itext7


【解决方案1】:

我已经解决了,
这个想法是: 1.我们需要保存没有水印的文件,这很简单:

 File docsFolder = new File(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_DOWNLOADS), "osary/estmara");
     String currentDate = new SimpleDateFormat("dd-MM-yyyy_hh_mm_aaa", Locale.getDefault()).format(new Date());
        String pdfname = myEstmaraa.getTalabId() + "_" + currentDate + ".pdf";
        pdfFile = new File(docsFolder, pdfname);
        OutputStream output = new FileOutputStream(pdfFile);
        Document document = new Document(PageSize.A4);
        document.setMargins(5, 5, 5, 5);
        PdfWriter PdfWriters = PdfWriter.getInstance(document, output);
        PdfWriters.createXmpMetadata();
        PdfWriters.setTagged();
        document.open();
        //todo 2 preparing Header and directions and margin row 0
        PdfPTable tableForRowZero = new PdfPTable(new float[]{1});
        tableForRowZero.setSpacingBefore(5);
        tableForRowZero.setRunDirection(PdfWriter.RUN_DIRECTION_RTL);
        tableForRowZero.getDefaultCell().setFixedHeight(34);
        tableForRowZero.setTotalWidth(PageSize.A4.getWidth());
        tableForRowZero.setWidthPercentage(100);
        tableForRowZero.setHeaderRows(0);
        tableForRowZero.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);
        cellss = new PdfPCell(new Phrase("رقم الاستمارة", FONT2));
        cellss.setHorizontalAlignment(Element.ALIGN_CENTER);
        cellss.setVerticalAlignment(Element.ALIGN_CENTER);
        cellss.setBackgroundColor(BaseColor.GRAY);
        tableForRowZero.addCell(cellss);
        tableForRowZero.setHeaderRows(0);
        cellss = new PdfPCell(new Phrase(String.valueOf(myEstmaraa.getTalabId()), FONT2));
        cellss.setHorizontalAlignment(Element.ALIGN_CENTER);
        cellss.setVerticalAlignment(Element.ALIGN_CENTER);
        tableForRowZero.addCell(cellss);
        document.add(tableForRowZero);
        document.close();

2.我们将打开文件但我们不能直接覆盖它, 所以:

一个。我们将它保存在带有水印的临时文件中并关闭它:

     File tempFile = new File(docsFolder.getPath(), "temp.pdf");
            com.itextpdf.kernel.pdf.PdfWriter TempWriter = new com.itextpdf.kernel.pdf.PdfWriter(tempFile);
            String font = "/res/font/arialbd.ttf";
            PdfFontFactory.register(font);
            FontProgram fontProgram = FontProgramFactory.createFont(font, true);
            PdfFont f = PdfFontFactory.createFont(fontProgram, PdfEncodings.IDENTITY_H);
            LanguageProcessor languageProcessor = new ArabicLigaturizer();
            com.itextpdf.kernel.pdf.PdfDocument tempPdfDoc = new com.itextpdf.kernel.pdf.PdfDocument(new PdfReader(pdfFile.getPath()), TempWriter);
            com.itextpdf.layout.Document TempDoc = new com.itextpdf.layout.Document(tempPdfDoc);
            com.itextpdf.layout.element.Paragraph paragraph0 = new com.itextpdf.layout.element.Paragraph(languageProcessor.process("الاستماره الالكترونية--الاستماره الالكترونية--الاستماره الالكترونية--الاستماره الالكترونية"))
                    .setFont(f).setBaseDirection(BaseDirection.RIGHT_TO_LEFT)
                    .setFontSize(15);
 Drawable d_ketm_estmara = getResources().getDrawable(R.drawable.ketm_estmara);
            Bitmap bitDw_estmara = ((BitmapDrawable) d_ketm_estmara).getBitmap();
            ByteArrayOutputStream stream_estmara = new ByteArrayOutputStream();
            bitDw_estmara.compress(Bitmap.CompressFormat.PNG, 100, stream_estmara);
            byte[] data = stream_estmara.toByteArray();
            ImageData img = ImageDataFactory.create(data);
            PdfExtGState gs1 = new PdfExtGState().setFillOpacity(0.2f);
            for (int i = 1; i <= tempPdfDoc.getNumberOfPages(); i++) {
                PdfPage pdfPage = tempPdfDoc.getPage(i);
                com.itextpdf.kernel.geom.Rectangle pageSize = pdfPage.getPageSize();
                float x = (pageSize.getLeft() + pageSize.getRight()) / 2;
                float y = (pageSize.getTop() + pageSize.getBottom()) / 3;
                PdfCanvas over = new PdfCanvas(pdfPage);
                over.saveState();
                over.setExtGState(gs1);
                TempDoc.showTextAligned(paragraph0, 300, 760, i, TextAlignment.CENTER, VerticalAlignment.TOP, 0);
 float leftImage = 20;
                float bottomImage = 120;
                float rightImage = 550;
                float topImage = 720;
                over.addImageWithTransformationMatrix(img, rightImage, 0, 0, topImage, leftImage, bottomImage, true);
                over.restoreState();
            }

            TempDoc.close();
            tempPdfDoc.close();

b.我们将打开临时文件并用旧名称保存:

            com.itextpdf.kernel.pdf.PdfDocument pdfDoc = new com.itextpdf.kernel.pdf.PdfDocument(new PdfReader(tempFile.getPath()), new com.itextpdf.kernel.pdf.PdfWriter(new File(docsFolder.getPath(), pdfname)));
            com.itextpdf.layout.Document doc = new com.itextpdf.layout.Document(pdfDoc);
            doc.close();
            pdfDoc.close();

【讨论】:

    猜你喜欢
    • 2018-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-04
    • 1970-01-01
    • 2017-12-19
    相关资源
    最近更新 更多