Esempio n. 1
0
        /// <summary>Creates a PdfFormXObject with the barcode.</summary>
        /// <param name="barColor">The color of the bars. It can be <CODE>null</CODE></param>
        /// <param name="textColor">The color of the text. It can be <CODE>null</CODE></param>
        /// <param name="document">The document</param>
        /// <returns>the XObject</returns>
        /// <seealso cref="PlaceBarcode(iText.Kernel.Pdf.Canvas.PdfCanvas, iText.Kernel.Colors.Color, iText.Kernel.Colors.Color)
        ///     "/>
        public virtual PdfFormXObject CreateFormXObject(Color barColor, Color textColor, PdfDocument document)
        {
            PdfFormXObject xObject = new PdfFormXObject((Rectangle)null);
            Rectangle      rect    = PlaceBarcode(new PdfCanvas(xObject, document), barColor, textColor);

            xObject.SetBBox(new PdfArray(rect));
            return(xObject);
        }
        private void CreateBlankN0()
        {
            n0 = new PdfFormXObject(new Rectangle(100, 100));
            n0.MakeIndirect(document);
            PdfCanvas canvas = new PdfCanvas(n0, document);

            canvas.WriteLiteral("% DSBlank\n");
        }
Esempio n. 3
0
        PdfTilingPattern BuildPattern(ImageBrush brush, XMatrix transform)
        {
            // Bounding box lays always at (0,0)
            XRect   bbox   = new XRect(0, 0, brush.Viewport.Width, brush.Viewport.Height);
            XMatrix matrix = transform;

            matrix.Prepend(new XMatrix(1, 0, 0, 1, brush.Viewport.X, brush.Viewport.Y));
            if (brush.Transform != null)
            {
                matrix.Prepend(new XMatrix(brush.Transform.Matrix.m11, brush.Transform.Matrix.m12, brush.Transform.Matrix.m21,
                                           brush.Transform.Matrix.m22, brush.Transform.Matrix.offsetX, brush.Transform.Matrix.offsetY));
            }

            // HACK by [email protected]
            // Avoid extra thin lines at the right and at the bottom of original image
            double xStep = brush.Viewport.Width + 1;
            double yStep = brush.Viewport.Height + 1;

            PdfTilingPattern pattern = Context.PdfDocument.Internals.CreateIndirectObject <PdfTilingPattern>();

            pattern.Elements.SetInteger(PdfTilingPattern.Keys.PatternType, 1); // Tiling
            pattern.Elements.SetInteger(PdfTilingPattern.Keys.PaintType, 1);   // Color
            pattern.Elements.SetInteger(PdfTilingPattern.Keys.TilingType, 3);  // Constant spacing and faster tiling
            pattern.Elements.SetMatrix(PdfTilingPattern.Keys.Matrix, matrix);
            pattern.Elements.SetRectangle(PdfTilingPattern.Keys.BBox, new PdfRectangle(bbox));
            pattern.Elements.SetReal(PdfTilingPattern.Keys.XStep, xStep);
            pattern.Elements.SetReal(PdfTilingPattern.Keys.YStep, yStep);

            // Set extended graphic state like Acrobat do
            PdfExtGState pdfExtGState = Context.PdfDocument.Internals.CreateIndirectObject <PdfExtGState>();

            pdfExtGState.SetDefault1();

            PdfFormXObject pdfForm = BuildForm(brush);

            PdfContentWriter writer = new PdfContentWriter(Context, pattern);

            writer.BeginContentRaw();

            // Acrobat 8 clips to bounding box, so do we
            //writer.WriteClip(bbox);

            XMatrix transformation = new XMatrix();
            double  dx             = brush.Viewport.Width / brush.Viewbox.Width * 96 / pdfForm.DpiX;
            double  dy             = brush.Viewport.Height / brush.Viewbox.Height * 96 / pdfForm.DpiY;

            transformation = new XMatrix(dx, 0, 0, dy, 0, 0);
            writer.WriteMatrix(transformation);
            writer.WriteGraphicsState(pdfExtGState);

            string name = writer.Resources.AddForm(pdfForm);

            writer.WriteLiteral(name + " Do\n");

            writer.EndContent();

            return(pattern);
        }
 /// <summary>Get Layer 2 of the appearance.</summary>
 /// <returns>layer 2</returns>
 public virtual PdfFormXObject GetLayer2()
 {
     if (n2 == null)
     {
         n2 = new PdfFormXObject(rect);
         n2.MakeIndirect(document);
     }
     return(n2);
 }
Esempio n. 5
0
        /// <summary>
        /// Gets the resource name of the specified form within this page.
        /// </summary>
        internal string GetFormName(XForm form)
        {
            PdfFormXObject pdfForm = _document.FormTable.GetForm(form);

            Debug.Assert(pdfForm != null);
            string name = Resources.AddForm(pdfForm);

            return(name);
        }
 /// <summary>Get Layer 0 of the appearance.</summary>
 /// <returns>layer 0</returns>
 public virtual PdfFormXObject GetLayer0()
 {
     if (n0 == null)
     {
         n0 = new PdfFormXObject(rect);
         n0.MakeIndirect(document);
     }
     return(n0);
 }
Esempio n. 7
0
        /// <summary>
        /// Builds a form XObject from a linear gradient brush that uses transparency.
        /// </summary>
        public static PdfFormXObject BuildFormFromLinearGradientBrush(
            DocumentRenderingContext context,
            LinearGradientBrush brush, PathGeometry geometry)
        {
            LinearShadingBuilder builder = new LinearShadingBuilder(context);
            PdfFormXObject       pdfForm = builder.BuildForm(brush, geometry);

            return(pdfForm);
        }
Esempio n. 8
0
        protected internal static ImageRenderer CreateLayoutedImageRenderer(float width, float height, Document document
                                                                            )
        {
            PdfFormXObject xObject  = new PdfFormXObject(new Rectangle(width, height));
            Image          img      = new Image(xObject);
            ImageRenderer  renderer = (ImageRenderer) new ImageRenderer(img).SetParent(document.GetRenderer());

            renderer.Layout(new LayoutContext(new LayoutArea(1, new Rectangle(1000, 1000))));
            return(renderer);
        }
        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());
        }
Esempio n. 10
0
        public Watermark(float x, float y, float width, float height, float opacity, PdfDocument pdfDoc)
        {
            Rectangle watermarkTrimmingRectangle = new Rectangle(x, y, width, height);

            _watermark = new PdfWatermarkAnnotation(watermarkTrimmingRectangle);

            _form = new PdfFormXObject(watermarkTrimmingRectangle);

            _canvas = new Canvas(opacity, pdfDoc, _form);
        }
Esempio n. 11
0
        public Image CreateBarcode(float xScale, float yScale, PdfDocument pdfDoc)
        {
            BarcodePDF417 barcode = new BarcodePDF417();

            barcode.SetCode("BarcodePDF417 barcode");
            PdfFormXObject barcodeObject = barcode.CreateFormXObject(ColorConstants.BLACK, pdfDoc);
            Image          barcodeImage  = new Image(barcodeObject).Scale(xScale, yScale);

            return(barcodeImage);
        }
        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());
        }
Esempio n. 13
0
        /// <summary>
        /// Gets the resource name of the specified form within this form.
        /// </summary>
        internal string GetFormName(XForm form)
        {
            Debug.Assert(IsTemplate, "This function is for form templates only.");
            PdfFormXObject pdfForm = _document.FormTable.GetForm(form);

            Debug.Assert(pdfForm != null);
            string name = Resources.AddForm(pdfForm);

            return(name);
        }
        private PdfFormXObject CreateFormXObject(PdfDocument pdfDocument)
        {
            ImageData      image    = ImageDataFactory.Create(sourceFolder + "itis.jpg");
            PdfFormXObject template = new PdfFormXObject(new Rectangle(image.GetWidth(), image.GetHeight()));
            PdfCanvas      canvas   = new PdfCanvas(template, pdfDocument);

            canvas.AddImage(image, 0, 0, image.GetWidth(), false).Flush();
            canvas.Release();
            template.Flush();
            return(template);
        }
 /// <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. 16
0
        private static void CopyPage(PdfCanvas canvas, PdfDocument srcDoc, PdfDocument pdfDoc,
                                     int pageNumber, float offsetX)
        {
            if (pageNumber > srcDoc.GetNumberOfPages())
            {
                return;
            }

            PdfFormXObject page = srcDoc.GetPage(pageNumber).CopyAsFormXObject(pdfDoc);

            canvas.AddXObjectAt(page, offsetX, 0);
        }
Esempio n. 17
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. 18
0
        public virtual void BasicIntegrationTest()
        {
            String      filename = "basicIntegrationTest.pdf";
            PdfDocument doc      = new PdfDocument(new PdfWriter(destinationFolder + filename));

            doc.AddNewPage();
            PdfFormXObject form = SvgConverter.ConvertToXObject("<svg width='100pt' height='100pt' />", doc);

            new PdfCanvas(doc.GetPage(1)).AddXObject(form, new Rectangle(100, 100, 100, 100));
            doc.Close();
            NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(destinationFolder + filename, sourceFolder
                                                                             + "cmp_" + filename, destinationFolder, "diff_"));
        }
Esempio n. 19
0
        private static Image GetWatermarkedImage(PdfDocument pdfDoc, Image img, String watermark)
        {
            float          width    = img.GetImageScaledWidth();
            float          height   = img.GetImageScaledHeight();
            PdfFormXObject template = new PdfFormXObject(new Rectangle(width, height));

            new Canvas(template, pdfDoc)
            .Add(img)
            .SetFontColor(DeviceGray.WHITE)
            .ShowTextAligned(watermark, width / 2, height / 2, TextAlignment.CENTER, (float)Math.PI / 6)
            .Close();
            return(new Image(template));
        }
Esempio n. 20
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);
        }
Esempio n. 21
0
        private static void DrawFormXObjects(PdfPage page, PdfFont titleFont, PdfFont sectionFont)
        {
            PdfBrush brush    = new PdfBrush();
            PdfPen   blackPen = new PdfPen(PdfRgbColor.Black, 1);

            PdfRgbColor randomPenColor   = new PdfRgbColor();
            PdfPen      randomPen        = new PdfPen(randomPenColor, 1);
            PdfRgbColor randomBrushColor = new PdfRgbColor();
            PdfBrush    randomBrush      = new PdfBrush(randomBrushColor);

            page.Graphics.DrawString("Form XObjects", titleFont, brush, 20, 50);
            page.Graphics.DrawString("Scaling", sectionFont, brush, 20, 70);

            // Create the XObject content - random rectangles
            PdfFormXObject xobject = new PdfFormXObject(300, 300);
            Random         rnd     = new Random();

            for (int i = 0; i < 100; i++)
            {
                randomPenColor.R = (byte)rnd.Next(256);
                randomPenColor.G = (byte)rnd.Next(256);
                randomPenColor.B = (byte)rnd.Next(256);

                randomBrushColor.R = (byte)rnd.Next(256);
                randomBrushColor.G = (byte)rnd.Next(256);
                randomBrushColor.B = (byte)rnd.Next(256);

                double left        = rnd.NextDouble() * xobject.Width;
                double top         = rnd.NextDouble() * xobject.Height;
                double width       = rnd.NextDouble() * xobject.Width;
                double height      = rnd.NextDouble() * xobject.Height;
                double orientation = rnd.Next(360);
                xobject.Graphics.DrawRectangle(randomPen, randomBrush, left, top, width, height, orientation);
            }

            xobject.Graphics.DrawRectangle(blackPen, 0, 0, xobject.Width, xobject.Height);
            xobject.Graphics.CompressAndClose();

            // Draw the form XObject 3 times on the page at different sizes.
            page.Graphics.DrawFormXObject(xobject, 3, 90, 100, 100);
            page.Graphics.DrawFormXObject(xobject, 106, 90, 200, 200);
            page.Graphics.DrawFormXObject(xobject, 309, 90, 300, 300);

            page.Graphics.DrawString("Flipping", sectionFont, brush, 20, 420);
            page.Graphics.DrawFormXObject(xobject, 20, 440, 150, 150);
            page.Graphics.DrawFormXObject(xobject, 200, 440, 150, 150, 0, PdfFlipDirection.VerticalFlip);
            page.Graphics.DrawFormXObject(xobject, 20, 620, 150, 150, 0, PdfFlipDirection.HorizontalFlip);
            page.Graphics.DrawFormXObject(xobject, 200, 620, 150, 150, 0, PdfFlipDirection.VerticalFlip | PdfFlipDirection.HorizontalFlip);

            page.Graphics.CompressAndClose();
        }
Esempio n. 22
0
        public static void Gen(string dest)
        {
            PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
            Document    doc    = new Document(pdfDoc, new PageSize(60, 140));

            doc.SetMargins(5, 5, 5, 5);

            PdfFont   bold    = PdfFontFactory.CreateFont(StandardFonts.HELVETICA_BOLD);
            PdfFont   regular = PdfFontFactory.CreateFont(StandardFonts.HELVETICA);
            PdfFont   mrv39s  = PdfFontFactory.CreateFont(@"fonts/mrvcode39s.ttf", true);
            Paragraph p1      = new Paragraph();

            p1.Add(new Text("23").SetFont(bold).SetFontSize(12));
            p1.Add(new Text("000").SetFont(bold).SetFontSize(6));
            doc.Add(p1);

            Paragraph p2 = new Paragraph("T.T.C.").SetFont(regular).SetFontSize(6);

            p2.SetTextAlignment(TextAlignment.RIGHT);
            doc.Add(p2);

            // CODE 39
            Paragraph pc3 = new Paragraph("*10000100*").SetFont(mrv39s).SetFontSize(6);

            pc3.SetTextAlignment(TextAlignment.LEFT);
            pc3.SetRotationAngle(Math.PI / 2);
            doc.Add(pc3);

            Barcode39 barcode = new Barcode39(pdfDoc);

            barcode.SetCode("12345678");
            Rectangle      rect           = barcode.GetBarcodeSize();
            PdfFormXObject template       = new PdfFormXObject(new Rectangle(rect.GetWidth(), rect.GetHeight() + 10));
            PdfCanvas      templateCanvas = new PdfCanvas(template, pdfDoc);

            new Canvas(templateCanvas, pdfDoc, new Rectangle(rect.GetWidth(), rect.GetHeight() + 10))
            .ShowTextAligned(new Paragraph("DARK GRAY").SetFont(regular).SetFontSize(6), 0, rect.GetHeight() + 2, TextAlignment.LEFT);
            barcode.PlaceBarcode(templateCanvas, DeviceRgb.BLACK, DeviceRgb.BLACK);
            Image image = new Image(template);

            image.SetRotationAngle(Math.PI / 4);
            image.SetAutoScale(true);
            doc.Add(image);

            Paragraph p3 = new Paragraph("SMALL").SetFont(regular).SetFontSize(6);

            p3.SetTextAlignment(TextAlignment.CENTER);
            doc.Add(p3);

            doc.Close();
        }
Esempio n. 23
0
        protected void ManipulatePdf(string dest)
        {
            PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
            Document    doc    = new Document(pdfDoc, new PageSize(60, 140));

            doc.SetMargins(5, 5, 5, 5);

            PdfFont boldFont    = PdfFontFactory.CreateFont(StandardFonts.HELVETICA_BOLD);
            PdfFont regularFont = PdfFontFactory.CreateFont(StandardFonts.HELVETICA);

            Paragraph p1 = new Paragraph();

            p1.Add(new Text("23").SetFont(boldFont).SetFontSize(12));
            p1.Add(new Text("000").SetFont(boldFont).SetFontSize(6));
            doc.Add(p1);

            Paragraph p2 = new Paragraph("T.T.C.").SetFont(regularFont).SetFontSize(6);

            p2.SetTextAlignment(TextAlignment.RIGHT);
            doc.Add(p2);

            BarcodeEAN barcode = new BarcodeEAN(pdfDoc);

            barcode.SetCodeType(BarcodeEAN.EAN8);
            barcode.SetCode("12345678");

            Rectangle      rect        = barcode.GetBarcodeSize();
            PdfFormXObject formXObject = new PdfFormXObject(new Rectangle(rect.GetWidth(), rect.GetHeight() + 10));
            PdfCanvas      pdfCanvas   = new PdfCanvas(formXObject, pdfDoc);

            new Canvas(pdfCanvas, new Rectangle(rect.GetWidth(), rect.GetHeight() + 10))
            .ShowTextAligned(new Paragraph("DARK GRAY").SetFont(regularFont).SetFontSize(6), 0,
                             rect.GetHeight() + 2, TextAlignment.LEFT);
            barcode.PlaceBarcode(pdfCanvas, ColorConstants.BLACK, ColorConstants.BLACK);

            Image image = new Image(formXObject);

            image.SetRotationAngle(Math.PI / 2f);
            image.SetAutoScale(true);
            doc.Add(image);

            Paragraph p3 = new Paragraph("SMALL").SetFont(regularFont).SetFontSize(6);

            p3.SetTextAlignment(TextAlignment.CENTER);
            doc.Add(p3);

            doc.Close();
        }
 private PdfXObject TryResolveSvgImageSource(String src)
 {
     try {
         using (MemoryStream stream = new MemoryStream(src.GetBytes(System.Text.Encoding.UTF8))) {
             PdfFormXObject xObject = ProcessAsSvg(stream, context, null);
             if (xObject != null)
             {
                 return(xObject);
             }
         }
     }
     catch (Exception) {
     }
     //Logs an error in a higher-level method if null is returned
     return(null);
 }
Esempio n. 25
0
        protected void ManipulatePdf(String dest)
        {
            PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(dest));
            PdfCanvas   canvas = new PdfCanvas(pdfDoc.GetFirstPage().NewContentStreamBefore(),
                                               pdfDoc.GetFirstPage().GetResources(), pdfDoc);

            foreach (String path in EXTRA)
            {
                PdfDocument    srcDoc = new PdfDocument(new PdfReader(path));
                PdfFormXObject page   = srcDoc.GetFirstPage().CopyAsFormXObject(pdfDoc);
                canvas.AddXObjectAt(page, 0, 0);
                srcDoc.Close();
            }

            pdfDoc.Close();
        }
Esempio n. 26
0
 /// <summary>
 /// Method that will set properties to be inherited by this branch renderer's
 /// children and will iterate over all children in order to draw them.
 /// </summary>
 /// <param name="context">
 /// the object that knows the place to draw this element and
 /// maintains its state
 /// </param>
 protected internal override void DoDraw(SvgDrawContext context)
 {
     // if branch has no children, don't do anything
     if (GetChildren().Count > 0)
     {
         PdfStream stream = new PdfStream();
         stream.Put(PdfName.Type, PdfName.XObject);
         stream.Put(PdfName.Subtype, PdfName.Form);
         PdfFormXObject xObject   = (PdfFormXObject)PdfXObject.MakeXObject(stream);
         PdfCanvas      newCanvas = new PdfCanvas(xObject, context.GetCurrentCanvas().GetDocument());
         ApplyViewBox(context);
         bool overflowVisible = IsOverflowVisible(this);
         // TODO (DEVSIX-3482) Currently overflow logic works only for markers.  Update this code after the ticket will be finished.
         if (this is MarkerSvgNodeRenderer && overflowVisible)
         {
             WriteBBoxAccordingToVisibleOverflow(context, stream);
         }
         else
         {
             Rectangle bbBox = context.GetCurrentViewPort().Clone();
             stream.Put(PdfName.BBox, new PdfArray(bbBox));
         }
         if (this is MarkerSvgNodeRenderer)
         {
             ((MarkerSvgNodeRenderer)this).ApplyMarkerAttributes(context);
         }
         context.PushCanvas(newCanvas);
         // TODO (DEVSIX-3482) Currently overflow logic works only for markers. Update this code after the ticket will be finished.
         if (!(this is MarkerSvgNodeRenderer) || !overflowVisible)
         {
             ApplyViewportClip(context);
         }
         ApplyViewportTranslationCorrection(context);
         foreach (ISvgNodeRenderer child in GetChildren())
         {
             if (!(child is MarkerSvgNodeRenderer))
             {
                 newCanvas.SaveState();
                 child.Draw(context);
                 newCanvas.RestoreState();
             }
         }
         CleanUp(context);
         // transformation already happened in AbstractSvgNodeRenderer, so no need to do a transformation here
         context.GetCurrentCanvas().AddXObject(xObject, 0, 0);
     }
 }
Esempio n. 27
0
 public virtual void NoBoundingBoxOnXObjectTest()
 {
     NUnit.Framework.Assert.That(() => {
         PdfDocument document = new PdfDocument(new PdfWriter(new MemoryStream(), new WriterProperties().SetCompressionLevel
                                                                  (0)));
         document.AddNewPage();
         ISvgNodeRenderer processed  = SvgConverter.Process(SvgConverter.Parse("<svg />")).GetRootRenderer();
         PdfRootSvgNodeRenderer root = new PdfRootSvgNodeRenderer(processed);
         PdfFormXObject pdfForm      = new PdfFormXObject(new PdfStream());
         PdfCanvas canvas            = new PdfCanvas(pdfForm, document);
         SvgDrawContext context      = new SvgDrawContext(null, null);
         context.PushCanvas(canvas);
         root.Draw(context);
     }
                                 , NUnit.Framework.Throws.InstanceOf <SvgProcessingException>().With.Message.EqualTo(SvgLogMessageConstant.ROOT_SVG_NO_BBOX))
     ;
 }
        /// <exception cref="System.Exception"/>
        internal virtual byte[] CreatePdfWithXObject(String xobjectText)
        {
            MemoryStream byteStream  = new MemoryStream();
            PdfDocument  pdfDocument = new PdfDocument(new PdfWriter(byteStream).SetCompressionLevel(0));
            Document     document    = new Document(pdfDocument);

            document.Add(new Paragraph("A"));
            document.Add(new Paragraph("B"));
            PdfFormXObject template = new PdfFormXObject(new Rectangle(100, 100));

            new PdfCanvas(template, pdfDocument).BeginText().SetFontAndSize(PdfFontFactory.CreateFont(StandardFonts.HELVETICA
                                                                                                      ), 12).MoveText(5, template.GetHeight() - 5).ShowText(xobjectText).EndText();
            document.Add(new Image(template));
            document.Add(new Paragraph("C"));
            document.Close();
            return(byteStream.ToArray());
        }
        private byte[] CreatePDF(string html)
        {
            byte[] binData;
            using (var workStream = new MemoryStream())
            {
                var         pdfWriter = new PdfWriter(workStream);
                var         pdf       = new PdfDocument(pdfWriter);
                PdfDocument sourcePdf = new PdfDocument(new PdfReader(new MemoryStream(CreateDocument(html))));
                //Original page
                PdfPage        origPage = sourcePdf.GetPage(1);
                PdfFormXObject pageCopy = origPage.CopyAsFormXObject(pdf);
                //Original page size
                Rectangle orig = origPage.GetPageSizeWithRotation();

                //Просто сжимание в A4
                Rectangle tileSize = PageSize.A4.Rotate();

                // Transformation matrix//30 пунктов - это 20px справа и слева, 40 * 0,75
                AffineTransform transformationMatrix = new AffineTransform();
                if (tileSize.GetHeight() / orig.GetHeight() > 0.5)
                {
                    transformationMatrix = AffineTransform.GetScaleInstance((tileSize.GetWidth() - 30) / orig.GetWidth(), 0.5);
                }
                else
                {
                    transformationMatrix = AffineTransform.GetScaleInstance((tileSize.GetWidth() - 30) / orig.GetWidth(), (tileSize.GetHeight() - 30) / orig.GetHeight());
                }
                PdfPage   transformPage   = pdf.AddNewPage(new PageSize(tileSize));
                PdfCanvas transformCanvas = new PdfCanvas(transformPage);
                transformCanvas.ConcatMatrix(transformationMatrix);
                if (tileSize.GetHeight() / orig.GetHeight() > 0.5)
                {
                    //20 пунктов сверху отступ
                    transformCanvas.AddXObject(pageCopy, 30, tileSize.GetHeight() + (tileSize.GetHeight() - orig.GetHeight()) - 20);
                }
                else
                {
                    transformCanvas.AddXObject(pageCopy, 30, 20);
                }
                pdf.Close();
                pdfWriter.Close();
                binData = workStream.ToArray();
            }

            return(binData);
        }
Esempio n. 30
0
        protected void ManipulatePdf(String dest)
        {
            PdfDocument srcDoc       = new PdfDocument(new PdfReader(SRC));
            Rectangle   pageSize     = srcDoc.GetFirstPage().GetPageSize();
            PdfDocument resultPdfDoc = new PdfDocument(new PdfWriter(dest));

            resultPdfDoc.SetDefaultPageSize(new PageSize(pageSize));
            resultPdfDoc.AddNewPage();

            PdfFormXObject pageXObject = srcDoc.GetFirstPage().CopyAsFormXObject(resultPdfDoc);
            Rectangle      toMove      = new Rectangle(100, 500, 100, 100);

            // Create a formXObject of a page content, in which the area to move is cut.
            PdfFormXObject formXObject1 = new PdfFormXObject(pageSize);
            PdfCanvas      canvas1      = new PdfCanvas(formXObject1, resultPdfDoc);

            canvas1.Rectangle(0, 0, pageSize.GetWidth(), pageSize.GetHeight());
            canvas1.Rectangle(toMove);

            // This method uses the even-odd rule to determine which regions lie inside the clipping path.
            canvas1.EoClip();
            canvas1.EndPath();
            canvas1.AddXObjectAt(pageXObject, 0, 0);

            // Create a formXObject of the area to move.
            PdfFormXObject formXObject2 = new PdfFormXObject(pageSize);
            PdfCanvas      canvas2      = new PdfCanvas(formXObject2, resultPdfDoc);

            canvas2.Rectangle(toMove);

            // This method uses the nonzero winding rule to determine which regions lie inside the clipping path.
            canvas2.Clip();
            canvas2.EndPath();
            canvas2.AddXObjectAt(pageXObject, 0, 0);

            PdfCanvas canvas = new PdfCanvas(resultPdfDoc.GetFirstPage());

            canvas.AddXObjectAt(formXObject1, 0, 0);

            // Add the area to move content, shifted 10 points to the left and 2 points to the bottom.
            canvas.AddXObjectAt(formXObject2, -20, -2);

            srcDoc.Close();
            resultPdfDoc.Close();
        }
Esempio n. 31
0
        private static void DrawFormXObjects(PdfPage page, PdfFont titleFont, PdfFont sectionFont)
        {
            PdfBrush brush = new PdfBrush();
            PdfPen blackPen = new PdfPen(PdfRgbColor.Black, 1);

            PdfRgbColor randomPenColor = new PdfRgbColor();
            PdfPen randomPen = new PdfPen(randomPenColor, 1);
            PdfRgbColor randomBrushColor = new PdfRgbColor();
            PdfBrush randomBrush = new PdfBrush(randomBrushColor);

            page.Graphics.DrawString("Form XObjects", titleFont, brush, 20, 50);
            page.Graphics.DrawString("Scaling", sectionFont, brush, 20, 70);

            // Create the XObject content - random rectangles
            PdfFormXObject xobject = new PdfFormXObject(300, 300);
            Random rnd = new Random();
            for (int i = 0; i < 100; i++)
            {
                randomPenColor.R = (byte)rnd.Next(256);
                randomPenColor.G = (byte)rnd.Next(256);
                randomPenColor.B = (byte)rnd.Next(256);

                randomBrushColor.R = (byte)rnd.Next(256);
                randomBrushColor.G = (byte)rnd.Next(256);
                randomBrushColor.B = (byte)rnd.Next(256);

                double left = rnd.NextDouble() * xobject.Width;
                double top = rnd.NextDouble() * xobject.Height;
                double width = rnd.NextDouble() * xobject.Width;
                double height = rnd.NextDouble() * xobject.Height;
                double orientation = rnd.Next(360);
                xobject.Graphics.DrawRectangle(randomPen, randomBrush, left, top, width, height, orientation);
            }

            xobject.Graphics.DrawRectangle(blackPen, 0, 0, xobject.Width, xobject.Height);
            xobject.Graphics.CompressAndClose();

            // Draw the form XObject 3 times on the page at different sizes.
            page.Graphics.DrawFormXObject(xobject, 3, 90, 100, 100);
            page.Graphics.DrawFormXObject(xobject, 106, 90, 200, 200);
            page.Graphics.DrawFormXObject(xobject, 309, 90, 300, 300);

            page.Graphics.DrawString("Flipping", sectionFont, brush, 20, 420);
            page.Graphics.DrawFormXObject(xobject, 20, 440, 150, 150);
            page.Graphics.DrawFormXObject(xobject, 200, 440, 150, 150, 0, PdfFlipDirection.VerticalFlip);
            page.Graphics.DrawFormXObject(xobject, 20, 620, 150, 150, 0, PdfFlipDirection.HorizontalFlip);
            page.Graphics.DrawFormXObject(xobject, 200, 620, 150, 150, 0, PdfFlipDirection.VerticalFlip | PdfFlipDirection.HorizontalFlip);

            page.Graphics.CompressAndClose();
        }
Esempio n. 32
0
        private static void CreateRedactionAnnotations(PdfFixedDocument document, PdfFont font, Stream flashStream)
        {
            PdfBrush blackBrush = new PdfBrush();

            PdfPage page = document.Pages.Add();

            page.Graphics.DrawString("Redaction annotations", font, blackBrush, 50, 50);

            PdfStandardFont helvetica = new PdfStandardFont(PdfStandardFontFace.Helvetica, 10);
            page.Graphics.DrawString(
                "Open the file with Adobe Acrobat, right click on the annotation and select \"Apply redactions\". The text under the annotation will be redacted.",
                helvetica, blackBrush, 50, 110);

            PdfFormXObject redactionAppearance = new PdfFormXObject(250, 150);
            redactionAppearance.Graphics.DrawRectangle(new PdfBrush(PdfRgbColor.LightGreen),
                0, 0, redactionAppearance.Width, redactionAppearance.Height);
            PdfStringAppearanceOptions sao = new PdfStringAppearanceOptions();
            sao.Brush = new PdfBrush(PdfRgbColor.DarkRed);
            sao.Font = new PdfStandardFont(PdfStandardFontFace.HelveticaBold, 32);
            PdfStringLayoutOptions slo = new PdfStringLayoutOptions();
            slo.Width = redactionAppearance.Width;
            slo.Height = redactionAppearance.Height;
            slo.X = 0;
            slo.Y = 0;
            slo.HorizontalAlign = PdfStringHorizontalAlign.Center;
            slo.VerticalAlign = PdfStringVerticalAlign.Middle;
            redactionAppearance.Graphics.DrawString("This content has been redacted", sao, slo);

            PdfRedactionAnnotation redactionAnnotation = new PdfRedactionAnnotation();
            page.Annotations.Add(redactionAnnotation);
            redactionAnnotation.Author = "XFINIUM.PDF";
            redactionAnnotation.BorderColor = new PdfRgbColor(192, 0, 0);
            redactionAnnotation.BorderWidth = 1;
            redactionAnnotation.OverlayAppearance = redactionAppearance;
            redactionAnnotation.VisualRectangle = new PdfVisualRectangle(50, 100, 250, 150);
        }