Example #1
0
        public PdfPage(
            PdfResources resources,
            PdfContentStream contents,
            int pagewidth,
            int pageheight,
            PdfObjectId objectId)
            : base(objectId)
        {
            this[PdfName.Names.Type] = PdfName.Names.Page;
            this[PdfName.Names.Resources] = resources.GetReference();
            this[PdfName.Names.Contents] = contents.GetReference();

            PdfArray mediaBox = new PdfArray();
            mediaBox.Add(new PdfNumeric(0));
            mediaBox.Add(new PdfNumeric(0));
            mediaBox.Add(new PdfNumeric(pagewidth));
            mediaBox.Add(new PdfNumeric(pageheight));
            this[PdfName.Names.MediaBox] = mediaBox;
        }
Example #2
0
        public void StopRenderer()
        {
            fontSetup.AddToResources(new PdfFontCreator(pdfCreator), pdfCreator.GetResources());
            pdfCreator.OutputTrailer();

            pdfCreator       = null;
            pdfResources     = null;
            currentStream    = null;
            currentAnnotList = null;
            currentPage      = null;

            idReferences         = null;
            currentFontName      = String.Empty;
            currentFill          = null;
            prevUnderlineColor   = null;
            prevOverlineColor    = null;
            prevLineThroughColor = null;
            fontSetup            = null;
            fontInfo             = null;
        }
Example #3
0
        public PdfPage(
            PdfResources resources,
            PdfContentStream contents,
            int pagewidth,
            int pageheight,
            PdfObjectId objectId)
            : base(objectId)
        {
            this[PdfName.Names.Type]      = PdfName.Names.Page;
            this[PdfName.Names.Resources] = resources.GetReference();
            this[PdfName.Names.Contents]  = contents.GetReference();

            PdfArray mediaBox = new PdfArray();

            mediaBox.Add(new PdfNumeric(0));
            mediaBox.Add(new PdfNumeric(0));
            mediaBox.Add(new PdfNumeric(pagewidth));
            mediaBox.Add(new PdfNumeric(pageheight));
            this[PdfName.Names.MediaBox] = mediaBox;
        }
Example #4
0
        /**
         * render page into PDF
         *
         * @param page page to render
         */

        public void RenderPage(Page page)
        {
            BodyAreaContainer body;
            AreaContainer     before, after, start, end;

            currentStream = this.pdfCreator.MakeContentStream();
            body          = page.getBody();
            before        = page.getBefore();
            after         = page.getAfter();
            start         = page.getStart();
            end           = page.getEnd();

            this.currentFontName      = "";
            this.currentFontSize      = 0;
            this.currentLetterSpacing = Single.NaN;

            currentStream.BeginTextObject();

            RenderBodyAreaContainer(body);

            if (before != null)
            {
                RenderAreaContainer(before);
            }

            if (after != null)
            {
                RenderAreaContainer(after);
            }

            if (start != null)
            {
                RenderAreaContainer(start);
            }

            if (end != null)
            {
                RenderAreaContainer(end);
            }
            CloseText();

            // Bug fix for issue 1823
            this.currentLetterSpacing = Single.NaN;

            float w = page.getWidth();
            float h = page.GetHeight();

            currentStream.EndTextObject();

            var idList = new System.Collections.Generic.List <string>();

            foreach (string id in page.getIDList())
            {
                idList.Add(id);
            }

            currentPage = this.pdfCreator.MakePage(
                this.pdfResources, currentStream,
                Convert.ToInt32(Math.Round(w / 1000)),
                Convert.ToInt32(Math.Round(h / 1000)), idList.ToArray());

            if (page.hasLinks() || currentAnnotList != null)
            {
                if (currentAnnotList == null)
                {
                    currentAnnotList = this.pdfCreator.MakeAnnotList();
                }
                currentPage.SetAnnotList(currentAnnotList);

                ArrayList lsets = page.getLinkSets();
                foreach (LinkSet linkSet in lsets)
                {
                    linkSet.align();
                    String    dest     = linkSet.getDest();
                    LinkKind  linkType = linkSet.getLinkType();
                    ArrayList rsets    = linkSet.getRects();
                    foreach (LinkedRectangle lrect in rsets)
                    {
                        currentAnnotList.Add(
                            this.pdfCreator.MakeLink(lrect.getRectangle(),
                                                     dest, linkType).GetReference());
                    }
                }
                currentAnnotList = null;
            }
            else
            {
                // just to be on the safe side
                currentAnnotList = null;
            }

            // ensures that color is properly reset for blocks that carry over pages
            this.currentFill = null;
        }
Example #5
0
        /// <summary>
        /// Main method for running the sample.
        /// </summary>
        /// <param name="stream"></param>
        public static SampleOutputInfo[] Run()
        {
            // Create the pdf document
            PdfFixedDocument document = new PdfFixedDocument();
            // Create a new page in the document
            PdfPage page = document.Pages.Add();

            PdfBrush        brush     = new PdfBrush(PdfRgbColor.DarkRed);
            PdfStandardFont helvetica = new PdfStandardFont(PdfStandardFontFace.Helvetica, 36);

            page.Graphics.DrawString("Hello World", helvetica, brush, 100, 100);

            PdfContentStream cs = new PdfContentStream(page.Graphics);

            // Sets the stroke and fill colorspaces to DeviceRGB
            cs.SetStrokeColorSpace(new PdfRgbColorSpace());
            cs.SetFillColorSpace(new PdfRgbColorSpace());
            // Set stroke color to blue
            cs.SetStrokeColor(new double[] { 0, 0, 1 });
            // Set fill color to green
            cs.SetFillColor(new double[] { 0, 1, 0 });

            // Draw a line from (0, 0) to (page.Width/2, page.Height/2)
            // It will be drawn from top left corner to center of the page.
            cs.MoveTo(0, 0);
            cs.LineTo(page.Width / 2, page.Height / 2);
            cs.StrokePath();

            // Begin a text section
            cs.BeginText();
            cs.SetTextRendering(PdfTextRenderingMode.FillText);
            cs.SetTextMatrix(1, 0, 0, 1, 100, 150);
            cs.SetTextFontAndSize(helvetica, helvetica.Size);

            // This text will appear inverted because the coordinate system is in visual mode.
            byte[] binaryText = helvetica.EncodeString("Hello World");
            cs.ShowText(new PdfCosBinaryString(binaryText));
            cs.EndText();

            // Reset coordinate system and the current graphics state to default PDF
            cs.ResetPdfCoordinateSystem();
            // Sets the stroke and fill colorspaces to DeviceRGB
            cs.SetStrokeColorSpace(new PdfRgbColorSpace());
            cs.SetFillColorSpace(new PdfRgbColorSpace());
            // Set stroke color to blue
            cs.SetStrokeColor(new double[] { 0, 0, 1 });
            // Set fill color to green
            cs.SetFillColor(new double[] { 0, 1, 0 });

            // Draw a line from (0, 0) to (page.Width/2, page.Height/2)
            // It will be drawn from bottom left corner to center of the page because the coordinate system has been reset to default PDF.
            cs.MoveTo(0, 0);
            cs.LineTo(page.Width / 2, page.Height / 2);
            cs.StrokePath();

            // Draw the text again
            cs.BeginText();
            cs.SetTextRendering(PdfTextRenderingMode.FillText);
            cs.SetTextMatrix(1, 0, 0, 1, 100, 150);
            cs.SetTextFontAndSize(helvetica, helvetica.Size);

            // This text will appear ok.
            binaryText = helvetica.EncodeString("Hello World");
            cs.ShowText(new PdfCosBinaryString(binaryText));
            cs.EndText();

            // Restore the visual coordinate system
            cs.RestoreVisualCoordinateSystem();

            SampleOutputInfo[] output = new SampleOutputInfo[] { new SampleOutputInfo(document, "xfinium.pdf.sample.contentstream.pdf") };
            return(output);
        }
Example #6
0
        public void StopRenderer() {
            fontSetup.AddToResources(new PdfFontCreator(pdfDoc), pdfDoc.getResources());
            pdfDoc.outputTrailer();

            pdfDoc = null;
            pdfResources = null;
            currentStream = null;
            currentAnnotList = null;
            currentPage = null;

            idReferences = null;
            currentFontName = String.Empty;
            currentFill = null;
            prevUnderlineColor = null;
            prevOverlineColor = null;
            prevLineThroughColor = null;
            fontSetup = null;
            fontInfo = null;
        }
Example #7
0
        /**
        * render page into PDF
        *
        * @param page page to render
        */

        public void RenderPage(Page page) {
            BodyAreaContainer body;
            AreaContainer before, after, start, end;

            currentStream = this.pdfDoc.makeContentStream();
            body = page.getBody();
            before = page.getBefore();
            after = page.getAfter();
            start = page.getStart();
            end = page.getEnd();

            this.currentFontName = "";
            this.currentFontSize = 0;
            this.currentLetterSpacing = Single.NaN;

            currentStream.Write("BT\n");

            RenderBodyAreaContainer(body);

            if (before != null) {
                RenderAreaContainer(before);
            }

            if (after != null) {
                RenderAreaContainer(after);
            }

            if (start != null) {
                RenderAreaContainer(start);
            }

            if (end != null) {
                RenderAreaContainer(end);
            }
            CloseText();

            // Bug fix for issue 1823
            this.currentLetterSpacing = Single.NaN;

            float w = page.getWidth();
            float h = page.GetHeight();
            currentStream.Write("ET\n");

            currentPage = this.pdfDoc.makePage(
                this.pdfResources, currentStream,
                Convert.ToInt32(Math.Round(w/1000)),
                Convert.ToInt32(Math.Round(h/1000)), page);

            if (page.hasLinks() || currentAnnotList != null) {
                if (currentAnnotList == null) {
                    currentAnnotList = this.pdfDoc.makeAnnotList();
                }
                currentPage.SetAnnotList(currentAnnotList);

                ArrayList lsets = page.getLinkSets();
                foreach (LinkSet linkSet in lsets) {
                    linkSet.align();
                    String dest = linkSet.getDest();
                    int linkType = linkSet.getLinkType();
                    ArrayList rsets = linkSet.getRects();
                    foreach (LinkedRectangle lrect in rsets) {
                        currentAnnotList.Add(this.pdfDoc.makeLink(lrect.getRectangle(),
                                                                  dest, linkType).GetReference());
                    }
                }
                currentAnnotList = null;
            }
            else {
                // just to be on the safe side
                currentAnnotList = null;
            }

            // ensures that color is properly reset for blocks that carry over pages
            this.currentFill = null;
        }
Example #8
0
 public PdfContentStream makeContentStream()
 {
     PdfContentStream obj = new PdfContentStream(doc.NextObjectId());
     obj.AddFilter(new FlateFilter());
     this.objects.Add(obj);
     return obj;
 }
Example #9
0
        public PdfPage makePage(PdfResources resources, PdfContentStream contents,
                                int pagewidth, int pageheight, Page currentPage)
        {
            PdfPage page = new PdfPage(
                resources, contents,
                pagewidth, pageheight,
                doc.NextObjectId());

            if (currentPage != null)
            {
                foreach (string id in currentPage.getIDList())
                {
                    idReferences.setInternalGoToPageReference(id, page.GetReference());
                }
            }

            /* add it to the list of objects */
            this.objects.Add(page);

            page.SetParent(doc.Pages);
            doc.Pages.Kids.Add(page.GetReference());

            return page;
        }
Example #10
0
        /// <summary>
        /// Main method for running the sample.
        /// </summary>
        /// <param name="stream"></param>
        public static SampleOutputInfo[] Run()
        {
            // Create the pdf document
            PdfFixedDocument document = new PdfFixedDocument();
            // Create a new page in the document
            PdfPage page = document.Pages.Add();

            PdfBrush brush = new PdfBrush(PdfRgbColor.DarkRed);
            PdfStandardFont helvetica = new PdfStandardFont(PdfStandardFontFace.Helvetica, 36);
            page.Graphics.DrawString("Hello World", helvetica, brush, 100, 100);

            PdfContentStream cs = new PdfContentStream(page.Graphics);
            // Sets the stroke and fill colorspaces to DeviceRGB
            cs.SetStrokeColorSpace(new PdfRgbColorSpace());
            cs.SetFillColorSpace(new PdfRgbColorSpace());
            // Set stroke color to blue
            cs.SetStrokeColor(new double[] { 0, 0, 1 });
            // Set fill color to green
            cs.SetFillColor(new double[] { 0, 1, 0 });

            // Draw a line from (0, 0) to (page.Width/2, page.Height/2)
            // It will be drawn from top left corner to center of the page.
            cs.MoveTo(0, 0);
            cs.LineTo(page.Width / 2, page.Height / 2);
            cs.StrokePath();

            // Begin a text section
            cs.BeginText();
            cs.SetTextRendering(PdfTextRenderingMode.FillText);
            cs.SetTextMatrix(1, 0, 0, 1, 100, 150);
            cs.SetTextFontAndSize(helvetica, helvetica.Size);

            // This text will appear inverted because the coordinate system is in visual mode.
            byte[] binaryText = helvetica.EncodeString("Hello World");
            cs.ShowText(new PdfCosBinaryString(binaryText));
            cs.EndText();

            // Reset coordinate system and the current graphics state to default PDF
            cs.ResetPdfCoordinateSystem();
            // Sets the stroke and fill colorspaces to DeviceRGB
            cs.SetStrokeColorSpace(new PdfRgbColorSpace());
            cs.SetFillColorSpace(new PdfRgbColorSpace());
            // Set stroke color to blue
            cs.SetStrokeColor(new double[] { 0, 0, 1 });
            // Set fill color to green
            cs.SetFillColor(new double[] { 0, 1, 0 });

            // Draw a line from (0, 0) to (page.Width/2, page.Height/2)
            // It will be drawn from bottom left corner to center of the page because the coordinate system has been reset to default PDF.
            cs.MoveTo(0, 0);
            cs.LineTo(page.Width / 2, page.Height / 2);
            cs.StrokePath();

            // Draw the text again
            cs.BeginText();
            cs.SetTextRendering(PdfTextRenderingMode.FillText);
            cs.SetTextMatrix(1, 0, 0, 1, 100, 150);
            cs.SetTextFontAndSize(helvetica, helvetica.Size);

            // This text will appear ok.
            binaryText = helvetica.EncodeString("Hello World");
            cs.ShowText(new PdfCosBinaryString(binaryText));
            cs.EndText();

            // Restore the visual coordinate system
            cs.RestoreVisualCoordinateSystem();

            SampleOutputInfo[] output = new SampleOutputInfo[] { new SampleOutputInfo(document, "xfinium.pdf.sample.contentstream.pdf") };
            return output;
        }
Example #11
0
 public PdfContents(PdfContentStream stream)
 {
     this.Value = (IPdfObject)stream;
 }
Example #12
0
        public async Task SaveAsync(Stream stream)
        {
            var pdfDocumentCatalog = new PdfDocumentCatalog();
            var pdfPageTree        = new PdfPageTree();

            pdfDocumentCatalog.PagesReference = pdfPageTree.Reference;

            var pdfFonts             = new List <PdfFont>();
            var pdfFontDescriptors   = new List <PdfFontDescriptor>();
            var pdfCharWidthsObjects = new List <PdfCharWidths>();
            var pdfFontStreams       = new List <PdfFontStream>();
            var fontToPdfFont        = new Dictionary <Font, PdfFont>();

            foreach (var font in Fonts)
            {
                var fontStream = new PdfFontStream();
                fontStream.Filter = PdfStreamFilter.FlateDecode;
                fontStream.Stream = new PdfStream(File.ReadAllBytes(font.FileName));
                pdfFontStreams.Add(fontStream);

                var fontInfo = font.FontInfo;
                var factor   = 1000.0 / fontInfo.HeadTable.UnitsPerEm;

                var charWidths = new int[129];
                for (int i = 0; i < 129; i++)
                {
                    fontInfo.CharacterMapTable.Encodings.Last().Value.TryGetGlyphId(i, out var glyphIndex);
                    charWidths[i] = fontInfo.HorizontalMetricsTable.HMetrics[glyphIndex].AdvanceWidth;  // Don't normalize

                    //fontInfo.CharacterMapTable.Encodings.Last().Value.TryGetGlyphId(i, out var glyphIndex);
                    //var blockLocation = fontInfo.IndexLocationTable.GetLocation(glyphIndex);
                    //var glyphHeader = fontInfo.GlyphTable.ReadHeader(blockLocation);
                    //charWidths[i] = glyphHeader.XMax - glyphHeader.XMin;
                }
                var pdfCharWidths = new PdfCharWidths {
                    Widths = new PdfArray(charWidths.Select(x => (PdfObject) new PdfReal(Normalize(x, factor))).ToList())
                };
                pdfCharWidthsObjects.Add(pdfCharWidths);

                var pdfFontDescriptor = new PdfFontDescriptor
                {
                    Ascent   = new PdfInteger(Normalize(fontInfo.HorizontalHeaderTable.Ascender, factor)),
                    Descent  = new PdfInteger(Normalize(fontInfo.HorizontalHeaderTable.Descender, factor)),
                    FontName = new PdfName(font.Name),
                    FontBBox = new PdfRectangle(Normalize(fontInfo.HeadTable.XMin, factor),
                                                Normalize(fontInfo.HeadTable.YMin, factor),
                                                Normalize(fontInfo.HeadTable.XMax, factor),
                                                Normalize(fontInfo.HeadTable.YMax, factor)),
                    FontWeight  = new PdfInteger(fontInfo.Os2Table.UsWeightClass),
                    AvgWidth    = new PdfInteger(Normalize(fontInfo.Os2Table.XAvgCharWidth, factor)),
                    CapHeight   = new PdfInteger(Normalize(fontInfo.Os2Table.SCapHeight, factor)),
                    ItalicAngle = new PdfReal(Normalize((double)fontInfo.PostScriptTable.ItalicAngle, factor)),
                    // MaxWidth = new PdfInteger(0),        // TODO
                    // XHeight = new PdfInteger(0),         // TODO
                    StemV     = new PdfInteger(50),         // TODO
                    Flags     = new PdfInteger(32),         // TODO
                    FontFile2 = new PdfIndirectObjectReference(fontStream)
                };
                pdfFontDescriptors.Add(pdfFontDescriptor);

                var pdfFont = new PdfFont
                {
                    Subtype        = new PdfName(font.Type),
                    BaseFont       = new PdfName(font.Name),
                    Encoding       = new PdfName(font.Encoding.ToString()),
                    FontDescriptor = pdfFontDescriptor.Reference,
                    Widths         = pdfCharWidths.Reference,
                    FirstChar      = new PdfInteger(0),
                    LastChar       = new PdfInteger(127)
                };
                pdfFonts.Add(pdfFont);
                fontToPdfFont[font] = pdfFont;
            }

            pdfPageTree.MediaBox  = new PdfRectangle(0, 0, DefaultPageWidth, DefaultPageHeight);
            pdfPageTree.Resources = new PdfResources
            {
                Fonts = new PdfFontResources()
            };
            foreach (var font in Fonts)
            {
                pdfPageTree.Resources.Fonts.Add($"F{_nextFontId++}", fontToPdfFont[font].Reference);
            }

            var pdfContentStreams = new List <PdfContentStream>();
            var pdfPages          = new List <PdfPage>();

            foreach (var page in Pages)
            {
                var pdfPage = new PdfPage();
                pdfPages.Add(pdfPage);

                pdfPage.Parent = pdfPageTree.Reference;
                if (page.Unit != 1.0)
                {
                    pdfPage.UserUnit = new PdfReal(page.Unit);
                }
                if (page.Width != DefaultPageWidth || page.Height != DefaultPageHeight)
                {
                    pdfPage.MediaBox = new PdfRectangle(0, 0, page.Width, page.Height);
                }

                var instructions = page.Paint();
                if (!string.IsNullOrWhiteSpace(instructions))
                {
                    var pdfContentStream = new PdfContentStream
                    {
                        Stream = new PdfStream(Encoding.ASCII.GetBytes(instructions)),
                        // Filter = PdfStreamFilter.FlateDecode // Temporarily no using. Uncomment after development complete
                    };
                    pdfContentStreams.Add(pdfContentStream);
                    pdfPage.Contents = pdfContentStream.Reference;
                }
            }
            pdfPageTree.Kids = pdfPages.Select(x => x.Reference).ToList();

            var writer = new PdfWriter(stream);
            await writer.WriteAsync(pdfDocumentCatalog);

            await writer.WriteAsync(pdfPageTree);

            foreach (var pdfFont in pdfFonts)
            {
                await writer.WriteAsync(pdfFont);
            }
            foreach (var pdfFontDescriptor in pdfFontDescriptors)
            {
                await writer.WriteAsync(pdfFontDescriptor);
            }
            foreach (var pdfCharWidths in pdfCharWidthsObjects)
            {
                await writer.WriteAsync(pdfCharWidths);
            }
            foreach (var pdfFontStream in pdfFontStreams)
            {
                await writer.WriteAsync(pdfFontStream);
            }
            foreach (var pdfPage in pdfPages)
            {
                await writer.WriteAsync(pdfPage);
            }
            foreach (var pdfContentStream in pdfContentStreams)
            {
                await writer.WriteAsync(pdfContentStream);
            }
            await writer.CloseAsync(pdfDocumentCatalog, null);
        }