将itext Watermark添加到Android Java PDF

发布于 2025-01-21 06:48:41 字数 6353 浏览 0 评论 0 原文

我需要在我的PDF Android Java PDF文件中添加Itext Watermark 我用于创建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:

,我遇到的问题就是这一行:

        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();
            }

I need to add an itext watermark to my pdf android java pdf file
my sample current code for creating the pdf file:

   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();

i have tried this code but it for desktop java:
enter link description here

and the problem that i faced is this line:

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

when i change it to android i face a problem, i tried it like:

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

it gives me this hint:

Cannot resolve constructor 'PdfWriter(java.lang.String)'

the code i tried to make watermark:

   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();

i tried also to add png image and set its opacity but it cover the content

      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();
            }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

倾城月光淡如水﹏ 2025-01-28 06:48:41

我解决了,
这个想法是:
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();

i have solved it,
the idea is:
1.we need to save the file with out water mark ,and that was easy:

 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.we will open the file but we can not override it directly,
so:

a. we will save it in a temp file with the watermark and close it:

     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. we will open the temp file and save it with the old name:

            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();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文