public virtual void CheckInvalidFontGlyphsTest()
 {
     using (MemoryStream bos = new MemoryStream()) {
         using (PdfWriter writer = new PdfWriter(bos)) {
             using (PdfDocument document = new PdfDocument(writer)) {
                 document.AddNewPage();
                 PdfFormXObject formXObject = new PdfFormXObject(new Rectangle(0f, 0f));
                 formXObject.GetPdfObject().Put(PdfName.Subtype2, PdfName.PS);
                 PdfDictionary charProcs = new PdfDictionary();
                 charProcs.Put(PdfName.A, new PdfStream());
                 charProcs.Put(PdfName.B, formXObject.GetPdfObject());
                 PdfArray differences = new PdfArray();
                 differences.Add(new PdfNumber(41));
                 differences.Add(PdfName.A);
                 differences.Add(new PdfNumber(82));
                 differences.Add(PdfName.B);
                 PdfFont font = CreateFontWithCharProcsAndEncodingDifferences(document, charProcs, differences);
                 NUnit.Framework.Assert.That(() => {
                     pdfA2Checker.CheckFontGlyphs(font, null);
                 }
                                             , NUnit.Framework.Throws.InstanceOf <PdfAConformanceException>().With.Message.EqualTo(PdfAConformanceException.A_FORM_XOBJECT_DICTIONARY_SHALL_NOT_CONTAIN_SUBTYPE2_KEY_WITH_A_VALUE_OF_PS))
                 ;
             }
         }
     }
 }
Esempio n. 2
0
        /// <summary>Copies page as FormXObject to the specified document.</summary>
        /// <param name="toDocument">a document to copy to.</param>
        /// <returns>resultant XObject.</returns>
        /// <exception cref="System.IO.IOException"/>
        public virtual PdfFormXObject CopyAsFormXObject(PdfDocument toDocument)
        {
            PdfFormXObject  xObject      = new PdfFormXObject(GetCropBox());
            IList <PdfName> excludedKeys = new List <PdfName>(iText.IO.Util.JavaUtil.ArraysAsList(PdfName.MediaBox, PdfName
                                                                                                  .CropBox, PdfName.Contents));

            excludedKeys.AddAll(this.excludedKeys);
            PdfDictionary dictionary = GetPdfObject().CopyTo(toDocument, excludedKeys, true);

            xObject.GetPdfObject().GetOutputStream().Write(GetContentBytes());
            xObject.GetPdfObject().MergeDifferent(dictionary);
            return(xObject);
        }
        protected void ManipulatePdf(String dest)
        {
            PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));

            Rectangle rect             = new Rectangle(36, 700, 100, 100);
            String    embeddedFileName = "test.docx";

            // the 3rd argument is the file description.
            // the 5th argument is the mime-type of the embedded file;
            // the 6th argument is the AFRelationship key value.
            PdfFileSpec   fileSpec   = PdfFileSpec.CreateEmbeddedFileSpec(pdfDoc, PATH, null, embeddedFileName, null, null);
            PdfAnnotation attachment = new PdfFileAttachmentAnnotation(rect, fileSpec);

            // This method sets the text that will be displayed for the annotation or the alternate description,
            // if this type of annotation does not display text.
            attachment.SetContents("Click me");

            // Create XObject and draw it with the imported image on the canvas
            // to add XObject as normal appearance.
            PdfFormXObject xObject   = new PdfFormXObject(rect);
            ImageData      imageData = ImageDataFactory.Create(IMG);
            PdfCanvas      canvas    = new PdfCanvas(xObject, pdfDoc);

            canvas.AddImageFittedIntoRectangle(imageData, rect, true);
            attachment.SetNormalAppearance(xObject.GetPdfObject());

            pdfDoc.AddNewPage().AddAnnotation(attachment);

            pdfDoc.Close();
        }
        public void CreatePdf(String filename)
        {
            PdfDocument pdfDoc = new PdfDocument(new PdfWriter(filename));
            Document    doc    = new Document(pdfDoc);

            doc.Add(new Paragraph("Hello World!"));

            // Create a signature form field
            PdfFormField field = PdfFormField.CreateSignature(pdfDoc,
                                                              new Rectangle(72, 632, 200, 100));

            field.SetFieldName(SIGNAME);
            field.SetPage(1);

            // Set the widget properties
            field.GetWidgets()[0].SetHighlightMode(PdfAnnotation.HIGHLIGHT_INVERT).SetFlags(PdfAnnotation.PRINT);

            PdfDictionary mkDictionary = field.GetWidgets()[0].GetAppearanceCharacteristics();

            if (null == mkDictionary)
            {
                mkDictionary = new PdfDictionary();
            }

            PdfArray black = new PdfArray();

            black.Add(new PdfNumber(ColorConstants.BLACK.GetColorValue()[0]));
            black.Add(new PdfNumber(ColorConstants.BLACK.GetColorValue()[1]));
            black.Add(new PdfNumber(ColorConstants.BLACK.GetColorValue()[2]));
            mkDictionary.Put(PdfName.BC, black);

            PdfArray white = new PdfArray();

            white.Add(new PdfNumber(ColorConstants.WHITE.GetColorValue()[0]));
            white.Add(new PdfNumber(ColorConstants.WHITE.GetColorValue()[1]));
            white.Add(new PdfNumber(ColorConstants.WHITE.GetColorValue()[2]));
            mkDictionary.Put(PdfName.BG, white);

            field.GetWidgets()[0].SetAppearanceCharacteristics(mkDictionary);

            PdfAcroForm.GetAcroForm(pdfDoc, true).AddField(field);

            Rectangle      rect    = new Rectangle(0, 0, 200, 100);
            PdfFormXObject xObject = new PdfFormXObject(rect);
            PdfCanvas      canvas  = new PdfCanvas(xObject, pdfDoc);

            canvas
            .SetStrokeColor(ColorConstants.BLUE)
            .SetFillColor(ColorConstants.LIGHT_GRAY)
            .Rectangle(0 + 0.5, 0 + 0.5, 200 - 0.5, 100 - 0.5)
            .FillStroke()
            .SetFillColor(ColorConstants.BLUE);
            new Canvas(canvas, rect).ShowTextAligned("SIGN HERE", 100, 50,
                                                     TextAlignment.CENTER, (float)(Math.PI / 180) * 25);

            // Note that Acrobat doesn't show normal appearance in the highlight mode.
            field.GetWidgets()[0].SetNormalAppearance(xObject.GetPdfObject());

            doc.Close();
        }
Esempio n. 5
0
        private void EnsureTransparencyObjectsNotEmpty()
        {
            PdfFormXObject formXObject = new PdfFormXObject(new Rectangle(0f, 0f));

            formXObject.SetGroup(new PdfTransparencyGroup());
            pdfA2Checker.CheckFormXObject(formXObject.GetPdfObject());
        }
            public override void Draw(DrawContext context)
            {
                int          pageNumber = GetOccupiedArea().GetPageNumber();
                Rectangle    bbox       = GetInnerAreaBBox();
                PdfDocument  pdf        = context.GetDocument();
                PdfAcroForm  form       = PdfAcroForm.GetAcroForm(pdf, true);
                PdfFormField chk        = PdfFormField.CreateRadioButton(pdf, bbox, _group, _value, PdfAConformanceLevel.PDF_A_1B
                                                                         );

                chk.SetPage(pageNumber);
                chk.SetValue("Off");
                chk.RegenerateField();
                chk.SetVisibility(PdfFormField.VISIBLE);
                chk.SetBorderColor(ColorConstants.BLACK);
                chk.SetBackgroundColor(ColorConstants.WHITE);
                chk.SetReadOnly(true);
                PdfFormXObject appearance = new PdfFormXObject(bbox);
                PdfCanvas      canvas     = new PdfCanvas(appearance, pdf);

                canvas.SaveState().MoveTo(bbox.GetLeft(), bbox.GetBottom()).LineTo(bbox.GetRight(), bbox.GetBottom()).LineTo
                    (bbox.GetRight(), bbox.GetTop()).LineTo(bbox.GetLeft(), bbox.GetTop()).LineTo(bbox.GetLeft(), bbox.GetBottom
                                                                                                      ()).SetLineWidth(1f).Stroke().RestoreState();
                form.AddFieldAppearanceToPage(chk, pdf.GetPage(pageNumber));
                chk.SetAppearance(PdfName.N, "v1".Equals(_value) ? _value : "Off", appearance.GetPdfObject());
            }
        private void CheckInFormXObject(PdfObject @object)
        {
            String newContentString = PdfACheckerTestUtils.GetStreamWithValue(@object);

            byte[]     newContent = newContentString.GetBytes(System.Text.Encoding.UTF8);
            PdfStream  stream     = new PdfStream(newContent);
            PdfXObject xobject    = new PdfFormXObject(stream);

            pdfA1Checker.CheckFormXObject(xobject.GetPdfObject());
        }
        private PdfStream CreateAppearance(PdfADocument doc, Rectangle formRect)
        {
            PdfFormXObject form   = new PdfFormXObject(formRect);
            PdfCanvas      canvas = new PdfCanvas(form, doc);
            PdfFont        font   = PdfFontFactory.CreateFont(sourceFolder + "FreeSans.ttf", "WinAnsi", true);

            canvas.SetFontAndSize(font, 12);
            canvas.BeginText().SetTextMatrix(200, 50).ShowText("Hello World").EndText();
            return(form.GetPdfObject());
        }
 /// <summary>
 /// Creates a
 /// <see cref="PdfTrapNetworkAnnotation"/>
 /// instance.
 /// </summary>
 /// <remarks>
 /// Creates a
 /// <see cref="PdfTrapNetworkAnnotation"/>
 /// instance. Note that there shall be at most one trap network annotation
 /// per page, which shall be the last element in the page’s Annots array.
 /// TrapNet annotations are deprecated in PDF 2.0.
 /// </remarks>
 /// <param name="rect">
 /// the annotation rectangle, defining the location of the annotation on the page
 /// in default user space units. See
 /// <see cref="PdfAnnotation.SetRectangle(iText.Kernel.Pdf.PdfArray)"/>.
 /// </param>
 /// <param name="appearanceStream">
 /// the form XObject defining a trap network which body contains the graphics objects needed
 /// to paint the traps making up the trap network. Process colour model shall be defined for the
 /// appearance stream (see
 /// <see cref="iText.Kernel.Pdf.Xobject.PdfFormXObject.SetProcessColorModel(iText.Kernel.Pdf.PdfName)"/>.
 /// See also ISO-320001 Table 367 "Additional entries specific to a trap network appearance stream".
 /// </param>
 public PdfTrapNetworkAnnotation(Rectangle rect, PdfFormXObject appearanceStream)
     : base(rect)
 {
     if (appearanceStream.GetProcessColorModel() == null)
     {
         throw new PdfException("Process color model must be set in appearance stream for Trap Network annotation!"
                                );
     }
     SetNormalAppearance(appearanceStream.GetPdfObject());
     SetFlags(PdfAnnotation.PRINT | PdfAnnotation.READ_ONLY);
 }
Esempio n. 10
0
 /// <summary>
 /// Adds the given Form XObject to the current instance of
 /// <see cref="PdfResources"/>.
 /// </summary>
 /// <param name="form">Form XObject.</param>
 /// <param name="name">Preferred name for the given Form XObject.</param>
 /// <returns>
 /// the
 /// <see cref="PdfName"/>
 /// of the newly added resource
 /// </returns>
 public virtual PdfName AddForm(PdfFormXObject form, PdfName name)
 {
     if (GetResourceNames(PdfName.XObject).Contains(name))
     {
         name = AddResource(form, formNamesGen);
     }
     else
     {
         AddResource(form.GetPdfObject(), PdfName.XObject, name);
     }
     return(name);
 }
Esempio n. 11
0
 public virtual void CheckAppearanceStreamWithoutTransparencyGroup()
 {
     using (MemoryStream bos = new MemoryStream()) {
         using (PdfWriter writer = new PdfWriter(bos)) {
             using (PdfDocument document = new PdfDocument(writer)) {
                 PdfFormXObject formXObject = new PdfFormXObject(new Rectangle(0f, 0f));
                 PdfAnnotation  annotation  = new PdfPopupAnnotation(new Rectangle(0f, 0f));
                 annotation.SetNormalAppearance(formXObject.GetPdfObject());
                 PdfPage pageToCheck = document.AddNewPage();
                 pageToCheck.AddAnnotation(new PdfPopupAnnotation(new Rectangle(0f, 0f)));
                 pageToCheck.AddAnnotation(annotation);
                 EnsureTransparencyObjectsNotEmpty();
                 // no assertions as we want to check that no exceptions would be thrown
                 pdfA2Checker.CheckSinglePage(pageToCheck);
             }
         }
     }
 }
Esempio n. 12
0
 public virtual void CheckAppearanceStreamWithTransparencyGroup()
 {
     using (MemoryStream bos = new MemoryStream()) {
         using (PdfWriter writer = new PdfWriter(bos)) {
             using (PdfDocument document = new PdfDocument(writer)) {
                 PdfFormXObject formXObject = new PdfFormXObject(new Rectangle(0f, 0f));
                 formXObject.SetGroup(new PdfTransparencyGroup());
                 PdfAnnotation annotation = new PdfPopupAnnotation(new Rectangle(0f, 0f));
                 annotation.SetNormalAppearance(formXObject.GetPdfObject());
                 PdfPage pageToCheck = document.AddNewPage();
                 pageToCheck.AddAnnotation(new PdfPopupAnnotation(new Rectangle(0f, 0f)));
                 pageToCheck.AddAnnotation(annotation);
                 NUnit.Framework.Assert.That(() => {
                     pdfA2Checker.CheckSinglePage(pageToCheck);
                 }
                                             , NUnit.Framework.Throws.InstanceOf <PdfAConformanceException>().With.Message.EqualTo(PdfAConformanceException.THE_DOCUMENT_DOES_NOT_CONTAIN_A_PDFA_OUTPUTINTENT_BUT_PAGE_CONTAINS_TRANSPARENCY_AND_DOES_NOT_CONTAIN_BLENDING_COLOR_SPACE))
                 ;
             }
         }
     }
 }
Esempio n. 13
0
        protected void ManipulatePdf(String dest)
        {
            PdfDocument    pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(dest));
            ImageData      img    = ImageDataFactory.Create(IMG);
            float          width  = img.GetWidth();
            float          height = img.GetHeight();
            PdfFormXObject xObj   = new PdfFormXObject(new Rectangle(width, height));

            PdfCanvas canvas = new PdfCanvas(xObj, pdfDoc);

            canvas.AddImageAt(img, 0, 0, false);

            Rectangle          location = new Rectangle(36, 770 - height, width, height);
            PdfStampAnnotation stamp    = new PdfStampAnnotation(location);

            stamp.SetStampName(new PdfName("ITEXT"));
            stamp.SetNormalAppearance(xObj.GetPdfObject());

            // Set to print the annotation when the page is printed
            stamp.SetFlags(PdfAnnotation.PRINT);
            pdfDoc.GetFirstPage().AddAnnotation(stamp);

            pdfDoc.Close();
        }
Esempio n. 14
0
        public byte[] Add(string infile, string outFile)
        {
            PdfFont   baseFont = PdfFontFactory.CreateFont(StandardFonts.HELVETICA_BOLD, Encoding.ASCII.EncodingName, false);
            Rectangle pageSize;
            string    NoOfPagesPadded = string.Empty;
            string    PageNoPadded    = string.Empty;
            string    HdrLeft         = string.Empty;
            string    HdrRight        = string.Empty;

            int xLeft  = 30;
            int xRight = 110;  //was 100
            int xTop   = 30;

            float watermarkTrimmingRectangleWidth;  //= 300;
            float watermarkTrimmingRectangleHeight = 300;

            float formXOffset = 0;
            float formYOffset = -5;  // was zero  set to -5 because dangling letters (e.g. g) were being cut-off

            byte[] outByteFile;
            byte[] inByteFile = null;

            try
            {
                inByteFile = File.ReadAllBytes(infile);
                IRandomAccessSource inSourceFile = new RandomAccessSourceFactory().CreateSource(inByteFile);
                using (PdfReader reader = new PdfReader(inSourceFile, new ReaderProperties()).SetUnethicalReading(true))
                {
                    using (var outMemoryFile = new MemoryStream())
                    {
                        using (PdfWriter pdfWrite = new PdfWriter(outMemoryFile))
                        {
                            using (PdfDocument pdfDoc = new PdfDocument(reader, pdfWrite))
                            {
                                using (Document doc = new Document(pdfDoc))
                                {
                                    int n = pdfDoc.GetNumberOfPages();
                                    for (var i = 1; i <= n; i++)
                                    {
                                        // Remove annotation if it exists
                                        PdfDictionary pageDict = pdfDoc.GetPage(i).GetPdfObject();
                                        PdfArray      annots   = pageDict.GetAsArray(PdfName.Annots);
                                        if (annots != null)
                                        {
                                            for (int j = 0; j < annots.Size(); j++)
                                            {
                                                PdfDictionary annotation = annots.GetAsDictionary(j);
                                                if (PdfName.Watermark.Equals(annotation.GetAsName(PdfName.Subtype)))
                                                {
                                                    string NMvalue = annotation.GetAsString(PdfName.NM).GetValue();
                                                    if (NMvalue == AnnotName)
                                                    {
                                                        annotation.Clear();
                                                    }
                                                }
                                            }
                                        }
                                    }

                                    for (int i = 1; i <= n; i++)
                                    {
                                        PdfPage page = pdfDoc.GetPage(i);
                                        pageSize = page.GetMediaBox();

                                        watermarkTrimmingRectangleWidth = pageSize.GetWidth();
                                        float     PageWidth  = pageSize.GetWidth();
                                        float     PageHeight = pageSize.GetHeight();
                                        int       rotation   = page.GetRotation();
                                        Rectangle watermarkTrimmingRectangle = new Rectangle(pageSize.GetLeft() + xLeft, pageSize.GetTop() - xTop, watermarkTrimmingRectangleWidth, watermarkTrimmingRectangleHeight);

                                        PdfWatermarkAnnotation watermark = new PdfWatermarkAnnotation(watermarkTrimmingRectangle);

                                        watermark.SetName(new PdfString(AnnotName));
                                        Rectangle formRectangle = new Rectangle(formXOffset, formYOffset, watermarkTrimmingRectangleWidth, watermarkTrimmingRectangleHeight);

                                        PdfFormXObject form       = new PdfFormXObject(formRectangle); //Observation: font XObject will be resized to fit inside the watermark rectangle.  If it is larger, your text will be stretched.
                                        PdfCanvas      canvasOver = new PdfCanvas(form, pdfDoc);

                                        canvasOver.SetFillColor(iText.Kernel.Colors.ColorConstants.RED);
                                        canvasOver.SetFontAndSize(baseFont, 10);
                                        canvasOver.SaveState();

                                        string SDSNo = "z2345678";
                                        HdrLeft = CompanyName + $" SDS# {SDSNo}";
                                        //  HdrLeft = $"PWidth: {PageWidth.ToString()} rotation: {rotation.ToString()}";  //qqtempqq
                                        NoOfPagesPadded = (n.ToString());
                                        PageNoPadded    = i.ToString();
                                        HdrRight        = $"Page {PageNoPadded} of {NoOfPagesPadded}";
                                        //  HdrRight = $"PHeight: {PageHeight.ToString()}";  //qqtempqq
                                        canvasOver.BeginText()
                                        .SetColor(iText.Kernel.Colors.ColorConstants.RED, true)
                                        .SetFontAndSize(baseFont, 10)
                                        .ShowText(HdrLeft)
                                        .EndText();
                                        canvasOver.BeginText()
                                        .MoveText(formRectangle.GetRight() - xRight, 0)
                                        .SetColor(iText.Kernel.Colors.ColorConstants.RED, true)
                                        .SetFontAndSize(baseFont, 10)
                                        .ShowText(HdrRight)
                                        .EndText();
                                        canvasOver.SaveState();

                                        canvasOver.RestoreState();
                                        canvasOver.Release();

                                        watermark.SetAppearance(PdfName.N, new PdfAnnotationAppearance(form.GetPdfObject()));
                                        watermark.SetFlags(PdfAnnotation.PRINT);

                                        page.AddAnnotation(watermark);
                                    }
                                }
                            }
                            outByteFile = outMemoryFile.ToArray();
                        }
                    }
                }
                File.WriteAllBytes(outFile, outByteFile);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error:" + ex.ToString());
                return(inByteFile);

                throw;
            }
            return(outByteFile);
        }
Esempio n. 15
0
        /// <summary>
        /// Watermarks a PDF file.
        /// </summary>
        /// <paramref name="fileName"/>
        private void WatermarkPdf(string fileName)
        {
            var watermarkText   = _operation.WatermarkText;
            var sourceFile      = $"{_operation.SourcePath}\\{fileName}";
            var destinationPath = $"{_operation.DestinationPath}\\{PathWatermarked}";
            var destinationFile = $"{destinationPath}\\{fileName}";

            ValidatePath(destinationPath);

            const float watermarkTrimmingRectangleWidth  = 600;
            const float watermarkTrimmingRectangleHeight = 600;

            const float formWidth   = 300;
            const float formHeight  = 300;
            const float formXOffset = 0;
            const float formYOffset = 0;

            const float xTranslation = 50;
            const float yTranslation = 25;

            const double rotationInRads = Math.PI / 3;

            try
            {
                FontCache.ClearSavedFonts();
            }
            catch (Exception exception)
            {
                Log.Error(exception.Message);
            }

            var         font     = PdfFontFactory.CreateFont(StandardFonts.COURIER);
            const float fontSize = 119;

            using var reader = new PdfReader(new MemoryStream(File.ReadAllBytes(sourceFile)));
            using var pdfDoc = new PdfDocument(reader, new PdfWriter(destinationFile));
            var     numberOfPages = pdfDoc.GetNumberOfPages();
            PdfPage page          = null;

            for (var i = 1; i <= numberOfPages; i++)
            {
                page = pdfDoc.GetPage(i);

                var ps = page.GetPageSize();

                //Center the annotation
                var bottomLeftX = ps.GetWidth() / 2 - watermarkTrimmingRectangleWidth / 2;
                var bottomLeftY = ps.GetHeight() / 2 - watermarkTrimmingRectangleHeight / 2;
                var watermarkTrimmingRectangle = new Rectangle(bottomLeftX, bottomLeftY,
                                                               watermarkTrimmingRectangleWidth, watermarkTrimmingRectangleHeight);

                var watermark = new PdfWatermarkAnnotation(watermarkTrimmingRectangle);

                //Apply linear algebra rotation math
                //Create identity matrix
                var transform = new AffineTransform(); //No-args constructor creates the identity transform
                //Apply translation
                transform.Translate(xTranslation, yTranslation);
                //Apply rotation
                transform.Rotate(rotationInRads);

                var fixedPrint = new PdfFixedPrint();
                watermark.SetFixedPrint(fixedPrint);
                //Create appearance
                var formRectangle = new Rectangle(formXOffset, formYOffset, formWidth, formHeight);

                //Observation: font XObject will be resized to fit inside the watermark rectangle
                var form   = new PdfFormXObject(formRectangle);
                var gs1    = new PdfExtGState().SetFillOpacity(0.6f);
                var canvas = new PdfCanvas(form, pdfDoc);

                var transformValues = new float[6];
                transform.GetMatrix(transformValues);

                canvas.SaveState()
                .BeginText().SetColor(ColorConstants.GRAY, true).SetExtGState(gs1)
                .SetTextMatrix(transformValues[0], transformValues[1], transformValues[2], transformValues[3],
                               transformValues[4], transformValues[5])
                .SetFontAndSize(font, fontSize)
                .ShowText(watermarkText)
                .EndText()
                .RestoreState();

                canvas.Release();

                watermark.SetAppearance(PdfName.N, new PdfAnnotationAppearance(form.GetPdfObject()));
                watermark.SetFlags(PdfAnnotation.PRINT);

                page.AddAnnotation(watermark);
            }

            page?.Flush();
            pdfDoc.Close();
        }
        public bool AddWaterMarkerToPdf(string pdfFile, string destFile, string text, string fontFamily, string fontColor, int fontSize = 50)
        {
            if (File.Exists(pdfFile))
            {
                try
                {
                    using (var pr = new PdfReader(pdfFile))
                    {
                        var rgbColor = System.Drawing.ColorTranslator.FromHtml(fontColor);


                        PdfFont font = fontFamily.Contains("STSong") ? PdfFontFactory.CreateFont(fontFamily, "UniGB-UCS2-H", true)
                            : PdfFontFactory.CreateFont(fontFamily);//PdfFontFactory.CreateFont(fontFamily, "UniGB-UCS2-H", true);
                        if (font != null)
                        {
                            var       textLength = font.GetWidth(text, fontSize);
                            var       pw         = new PdfWriter(destFile);
                            var       pdfDoc     = new PdfDocument(pr, pw);
                            Rectangle ps;
                            PdfCanvas canvas;
                            var       pageCount = pdfDoc.GetNumberOfPages();
                            for (var i = 1; i < pageCount + 1; i++)
                            {
                                var page = pdfDoc.GetPage(i);
                                ps = page.GetPageSize();
                                float watermarkTrimmingRectangleWidth  = textLength; //Math.Min(ps.GetWidth(), ps.GetHeight());
                                float watermarkTrimmingRectangleHeight = watermarkTrimmingRectangleWidth;
                                var   rotationInRads = MathF.Atan2(ps.GetHeight(), ps.GetWidth());
                                //var angle = rotationInRads * 180f / MathF.PI;
                                float formWidth   = ps.GetWidth();  //watermarkTrimmingRectangleWidth;
                                float formHeight  = ps.GetHeight(); //watermarkTrimmingRectangleWidth;
                                float formXOffset = 0;
                                float formYOffset = 0;

                                float xTranslation = (formWidth - watermarkTrimmingRectangleWidth * MathF.Cos(rotationInRads)) / 2;
                                float yTranslation = (formHeight - watermarkTrimmingRectangleWidth * MathF.Sin(rotationInRads)) / 2;

                                //Center the annotation
                                Rectangle watermarkTrimmingRectangle = new Rectangle(0, 0, formWidth, formHeight);//watermarkTrimmingRectangleWidth, watermarkTrimmingRectangleWidth);

                                PdfWatermarkAnnotation watermark = new PdfWatermarkAnnotation(watermarkTrimmingRectangle);

                                //Apply linear algebra rotation math
                                //Create identity matrix
                                AffineTransform transform = new AffineTransform(); //No-args constructor creates the identity transform
                                                                                   //Apply translation
                                                                                   //transform.Translate(xTranslation, yTranslation);
                                                                                   //Apply rotation
                                transform.Translate(xTranslation, yTranslation);
                                transform.Rotate(rotationInRads);

                                PdfFixedPrint fixedPrint = new PdfFixedPrint();
                                watermark.SetFixedPrint(fixedPrint);
                                //Create appearance
                                Rectangle formRectangle = new Rectangle(formXOffset, formYOffset, formWidth, formHeight);

                                //Observation: font XObject will be resized to fit inside the watermark rectangle
                                PdfFormXObject form = new PdfFormXObject(formRectangle);
                                PdfExtGState   gs1  = new PdfExtGState().SetFillOpacity(rgbColor.A / 255f);
                                canvas = new PdfCanvas(form, pdfDoc);

                                float[] transformValues = new float[6];
                                transform.GetMatrix(transformValues);
                                canvas.SaveState()
                                .BeginText().SetFillColorRgb(rgbColor.R / 225f, rgbColor.G / 225f, rgbColor.B / 255f).SetExtGState(gs1)
                                .SetTextMatrix(transformValues[0], transformValues[1], transformValues[2], transformValues[3], transformValues[4], transformValues[5])
                                .SetFontAndSize(font, fontSize)
                                .ShowText(text)
                                .EndText()
                                .RestoreState();

                                canvas.Release();

                                watermark.SetAppearance(PdfName.N, new PdfAnnotationAppearance(form.GetPdfObject()));
                                watermark.SetFlags(PdfAnnotation.PRINT);

                                page.AddAnnotation(watermark);
                            }
                            pdfDoc.Close();
                        }
                        else
                        {
                            App.Current.Dispatcher.Invoke(() =>
                            {
                                MessageBoxX.Show($"没有找到字体{fontFamily},请确认已安装", "字体错误");
                            });
                            return(false);
                        }
                        return(true);
                    }
                }
                catch (Exception ex)
                {
                    Analytics.TrackEvent("PDFError", new Dictionary <string, string>
                    {
                        ["message"] = ex.ToString()
                    });
                }
                finally
                {
                    File.Delete(pdfFile);
                }
            }
            return(false);
        }
 public PdfPrinterMarkAnnotation(Rectangle rect, PdfFormXObject appearanceStream)
     : base(rect)
 {
     SetNormalAppearance(appearanceStream.GetPdfObject());
     SetFlags(PdfAnnotation.PRINT | PdfAnnotation.READ_ONLY);
 }
 public virtual iText.Kernel.Pdf.Annot.PdfAnnotationAppearance SetState(PdfName stateName, PdfFormXObject state
                                                                        )
 {
     GetPdfObject().Put(stateName, state.GetPdfObject());
     return(this);
 }
Esempio n. 19
0
 public void SetAnnotation()
 {
     _watermark.SetAppearance(PdfName.N, new PdfAnnotationAppearance(_form.GetPdfObject()));
     _watermark.SetFlags(PdfAnnotation.PRINT);
 }