Пример #1
0
        private void addtable(Document document, DataGridView tabla, int num_columns)
        {
            Table table = new Table(num_columns);

            table.SetWidth(UnitValue.CreatePercentValue(100));

            for (int i = 0; i < num_columns; i++)
            {
                Process(table, tabla.Columns[i].HeaderText + "", PdfFontFactory.CreateFont(StandardFonts.HELVETICA), false);
            }

            for (int i = 0; i < tabla.Rows.Count - 1; i++)
            {
                for (int j = 0; j < num_columns; j++)
                {
                    if (tabla.Columns[j].HeaderText + "" == "IMPORTE")
                    {
                        Process(table, "$" + tabla.Rows[i].Cells[j].Value + "", PdfFontFactory.CreateFont(StandardFonts.HELVETICA), false);
                    }
                    else if (tabla.Columns[j].HeaderText + "" == "VALOR UNITARIO")
                    {
                        Process(table, "$" + tabla.Rows[i].Cells[j].Value + "", PdfFontFactory.CreateFont(StandardFonts.HELVETICA), false);
                    }
                    else
                    {
                        Process(table, tabla.Rows[i].Cells[j].Value + "", PdfFontFactory.CreateFont(StandardFonts.HELVETICA), false);
                    }
                }
            }


            if (num_columns == 4)
            {
                add_iva_subtotal(document, table);
            }
            else
            {
                document.Add(table);
            }
        }
Пример #2
0
        public virtual void CreatePdf(String dest)
        {
            // Initialize PDF document
            PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
            // Initialize document
            Document document = new Document(pdf);
            Table    table    = new Table(UnitValue.CreatePercentArray(2)).UseAllAvailableWidth();
            PdfFont  font     = PdfFontFactory.CreateFont(StandardFonts.TIMES_ROMAN);

            table.AddCell(new Cell().Add(new Paragraph("Test 1")).SetHeight(50).SetDestination("Top"));
            Style style = new Style();

            style.SetBackgroundColor(ColorConstants.YELLOW);
            table.AddCell(new Cell().SetBorder(new DottedBorder(5)).Add(new Paragraph("Test 2")).AddStyle(style).SetRelativePosition(
                              10, 10, 50, 10));
            table.AddCell(new Cell().Add(new Paragraph("Test 3")).SetVerticalAlignment(VerticalAlignment.BOTTOM));
            table.AddCell(new Cell().Add(ParagraphProperties.GetNewParagraphInstance()).SetHyphenation(new HyphenationConfig
                                                                                                           ("en", "uk", 3, 3)));
            table.AddCell(new Cell().Add(new Paragraph("Rotated")).SetRotationAngle(Math.PI / 18).SetFont(font).SetFontSize(8).SetFontColor
                              (ColorConstants.RED));
            table.AddCell(new Cell().Add(new Paragraph("Centered")).SetTextAlignment(TextAlignment.CENTER).SetAction(PdfAction.CreateGoTo
                                                                                                                         ("Top")));
            table.AddCell(new Cell().Add(new Paragraph("Test 5")).SetBackgroundColor(ColorConstants.BLUE));
            table.AddCell(new Cell().Add(ParagraphProperties.GetNewParagraphInstance()).SetBackgroundColor(ColorConstants.RED).
                          SetPaddingLeft(20).SetPaddingRight(50));
            table.AddCell(new Cell().Add(new Paragraph("Test 7")).SetBackgroundColor(ColorConstants.RED));
            table.AddCell(new Cell().Add(new Paragraph("Test 8")).SetBackgroundColor(ColorConstants.BLUE).SetMarginBottom(10));
            table.AddCell(new Cell().Add(new Paragraph("Test 9")).SetBackgroundColor(ColorConstants.BLUE));
            table.AddCell(new Cell().Add(new Paragraph("Test 10")).SetBackgroundColor(ColorConstants.RED));
            table.AddCell(new Cell().Add(ParagraphProperties.GetNewParagraphInstance()).SetBackgroundColor(ColorConstants.RED).
                          SetMargin(50).SetPadding(30));
            table.AddCell(new Cell().Add(new Paragraph("Test 12")).SetBackgroundColor(ColorConstants.BLUE));
            document.Add(table);
            SolidBorder border = new SolidBorder(ColorConstants.RED, 2);
            Cell        cell   = new Cell().Add(new Paragraph("Test")).SetFixedPosition(100, 400, 350).SetBorder(border).SetBackgroundColor(ColorConstants
                                                                                                                                            .BLUE).SetHeight(100).SetHorizontalAlignment(HorizontalAlignment.CENTER);

            document.Add(cell);
            document.Close();
        }
Пример #3
0
        private void ManipulatePdf(String dest)
        {
            PdfFont font = PdfFontFactory.CreateFont(FONT, PdfEncodings.IDENTITY_H);

            Stream fileStream =
                new FileStream("../../../resources/data/sRGB_CS_profile.icm", FileMode.Open, FileAccess.Read);
            PdfADocument pdfDoc = new PdfADocument(new PdfWriter(dest), PdfAConformanceLevel.PDF_A_1A,
                                                   new PdfOutputIntent("Custom", "",
                                                                       null, "sRGB IEC61966-2.1", fileStream));

            pdfDoc.GetCatalog().SetLang(new PdfString("nl-nl"));

            pdfDoc.SetTagged();

            Document doc = new Document(pdfDoc);

            doc.SetMargins(MARGIN_OF_ONE_CM, MARGIN_OF_ONE_CM, MARGIN_OF_ONE_CM, MARGIN_OF_ONE_CM);

            PdfDocumentInfo info = pdfDoc.GetDocumentInfo();

            info
            .SetTitle("title")
            .SetAuthor("Author")
            .SetSubject("Subject")
            .SetCreator("Creator")
            .SetKeywords("Metadata, iText, PDF")
            .SetCreator("My program using iText")
            .AddCreationDate();

            Paragraph element = new Paragraph("Hello World").SetFont(font).SetFontSize(10);

            doc.Add(element);

            Image logoImage = new Image(ImageDataFactory.Create(LOGO));

            logoImage.GetAccessibilityProperties().SetAlternateDescription("Logo");
            doc.Add(logoImage);

            doc.Close();
        }
        public virtual void OneThaiWordSplitAcrossMultipleRenderersDistributePossibleBreakPoints()
        {
            PdfDocument  pdfDocument  = new PdfDocument(new PdfWriter(new MemoryStream()));
            Document     document     = new Document(pdfDocument);
            LineRenderer lineRenderer = new LineRenderer();

            lineRenderer.SetParent(document.GetRenderer());
            PdfFont font = PdfFontFactory.CreateFont(THAI_FONT, PdfEncodings.IDENTITY_H);

            for (int i = 0; i < THAI_WORD.Length; i++)
            {
                TextRenderer textRenderer = new TextRenderer(new Text(""));
                textRenderer.SetProperty(Property.FONT, font);
                textRenderer.SetText(new String(new char[] { THAI_WORD[i] }));
                lineRenderer.AddChild(textRenderer);
            }
            IList <int> possibleBreaks = new List <int>(1);

            possibleBreaks.Add(THAI_WORD.Length);
            lineRenderer.DistributePossibleBreakPointsOverSequentialTextRenderers(0, THAI_WORD.Length, possibleBreaks,
                                                                                  new List <int>());
            IList <IRenderer> childRenderers = lineRenderer.GetChildRenderers();

            for (int i = 0; i < THAI_WORD.Length; i++)
            {
                IList <int> possibleBreaksPerRenderer = ((TextRenderer)childRenderers[i]).GetSpecialScriptsWordBreakPoints(
                    );
                NUnit.Framework.Assert.IsNotNull(possibleBreaksPerRenderer);
                NUnit.Framework.Assert.AreEqual(1, possibleBreaksPerRenderer.Count);
                int breakPoint = possibleBreaksPerRenderer[0];
                if (i != THAI_WORD.Length - 1)
                {
                    NUnit.Framework.Assert.AreEqual(-1, breakPoint);
                }
                else
                {
                    NUnit.Framework.Assert.AreEqual(((TextRenderer)childRenderers[i]).Length(), breakPoint);
                }
            }
        }
Пример #5
0
        public static byte[] CreateLabels(IEnumerable <Expansion> selectedExpansions)
        {
            var garamond     = Path.Combine(CurrentPath, "Fonts", "GARA.TTF");
            var garamondBold = Path.Combine(CurrentPath, "Fonts", "GARABD.TTF");
            var font         = PdfFontFactory.CreateFont(garamond, true);
            var boldFont     = PdfFontFactory.CreateFont(garamondBold, true);

            var dividers = DataAccess.GetDividers()
                           .Where(divider => selectedExpansions.Contains(divider.Expansion))
                           .ToList();
            var drawActionRectangles = dividers
                                       .Select((divider) => new Action <PdfCanvas, Rectangle>(
                                                   (canvas, rectangle) =>
            {
                var centeringCursor          = new CenteringCursor(rectangle.GetTop(), rectangle.GetBottom());
                var topCursor                = centeringCursor.StartCursor;
                var bottomCursor             = centeringCursor.EndCursor;
                const float dummyCostPadding = -27f;
                topCursor.AdvanceCursor(rectangle.GetTop());
                bottomCursor.AdvanceCursor(rectangle.GetBottom());

                DrawBackground(canvas, rectangle, divider.Type);
                if (divider.Cost != null)
                {
                    DrawCost(canvas, rectangle, divider.Cost.Value, boldFont, topCursor);
                }
                else
                {
                    topCursor.AdvanceCursor(dummyCostPadding);
                }
                DrawExpansionLogo(canvas, rectangle, divider.Expansion.GetAbbreviation(), boldFont, bottomCursor);
                DrawName(canvas, rectangle, divider.Name, font, centeringCursor);
            }))
                                       .ToList();


            var drawActionRectangleQueue = new Queue <Action <PdfCanvas, Rectangle> >(drawActionRectangles);

            return(PdfGenerator.DrawRectangles(drawActionRectangleQueue, ColorConstants.WHITE));
        }
Пример #6
0
        public byte[] GenerateCoachCard(string coachId, PdfCoachCard values)
        {
            var filePath      = Path.Combine(_env.ContentRootPath, $"PDF/carte_coach_fillable.pdf");
            var savePath      = Path.Combine(_env.ContentRootPath, $"wwwroot/pdf/coachs/cards/{coachId}.pdf");
            var saveImagePath = Path.Combine(_env.ContentRootPath, $"wwwroot/pdf/coachs/cards/{coachId}.png");

            //var filePath = "/PDF/integration_coach_fillable.pdf";
            //var savePath = "/PDF/saved/toSave.pdf";

            PdfDocument pdf                 = new PdfDocument(new PdfReader(filePath), new PdfWriter(savePath));
            PdfAcroForm form                = PdfAcroForm.GetAcroForm(pdf, false);
            PdfFont     documentBoldFont    = PdfFontFactory.CreateFont(StandardFonts.HELVETICA_BOLD);
            PdfFont     documentRegularFont = PdfFontFactory.CreateFont(StandardFonts.HELVETICA);

            var fields = form.GetFormFields();

            fields["last_name"].SetFontSize(42);
            fields["last_name"].SetFont(documentBoldFont);
            fields["last_name"].SetValue(values.LastName);

            fields["first_name"].SetFontSize(42);
            fields["first_name"].SetFont(documentBoldFont);
            fields["first_name"].SetValue(values.FirstName);

            fields["birthdate"].SetFontSize(22);
            fields["birthdate"].SetFont(documentRegularFont);
            fields["birthdate"].SetValue(string.Format("{0:dd/MM/yyyy}", values.Birthdate));

            fields["validity_date"].SetFontSize(22);
            fields["validity_date"].SetFont(documentRegularFont);
            fields["validity_date"].SetValue(string.Format("{0:dd/MM/yyyy}", values.ValidityDate));

            PdfAcroForm.GetAcroForm(pdf, false).FlattenFields();

            pdf.Close();

            $"gs -sDEVICE=pngalpha -sOutputFile={saveImagePath} -r144 {savePath}".Bash();

            return(File.ReadAllBytes(saveImagePath));
        }
Пример #7
0
        public virtual void ImagesWithDifferentDepth()
        {
            String      outFileName = destinationFolder + "transparencyTest01.pdf";
            String      cmpFileName = sourceFolder + "cmp_transparencyTest01.pdf";
            PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName, new WriterProperties().SetCompressionLevel
                                                                        (CompressionConstants.NO_COMPRESSION)));
            PdfPage   page   = pdfDocument.AddNewPage(PageSize.A3);
            PdfCanvas canvas = new PdfCanvas(page);

            canvas.SetFillColor(ColorConstants.LIGHT_GRAY).Fill();
            canvas.Rectangle(80, 0, 700, 1200).Fill();
            canvas.SaveState().BeginText().MoveText(116, 1150).SetFontAndSize(PdfFontFactory.CreateFont(StandardFonts.
                                                                                                        HELVETICA), 14).SetFillColor(ColorConstants.MAGENTA).ShowText("8 bit depth PNG").EndText().RestoreState
                ();
            ImageData img = ImageDataFactory.Create(sourceFolder + "manualTransparency_8bit.png");

            canvas.AddImage(img, 100, 780, 200, false);
            canvas.SaveState().BeginText().MoveText(316, 1150).SetFontAndSize(PdfFontFactory.CreateFont(StandardFonts.
                                                                                                        HELVETICA), 14).SetFillColor(ColorConstants.MAGENTA).ShowText("24 bit depth PNG").EndText().RestoreState
                ();
            img = ImageDataFactory.Create(sourceFolder + "manualTransparency_24bit.png");
            canvas.AddImage(img, 300, 780, 200, false);
            canvas.SaveState().BeginText().MoveText(516, 1150).SetFontAndSize(PdfFontFactory.CreateFont(StandardFonts.
                                                                                                        HELVETICA), 14).SetFillColor(ColorConstants.MAGENTA).ShowText("32 bit depth PNG").EndText().RestoreState
                ();
            img = ImageDataFactory.Create(sourceFolder + "manualTransparency_32bit.png");
            canvas.AddImage(img, 500, 780, 200, false);
            canvas.SaveState().BeginText().MoveText(116, 650).SetFontAndSize(PdfFontFactory.CreateFont(StandardFonts.HELVETICA
                                                                                                       ), 16).SetFillColor(ColorConstants.MAGENTA).ShowText("GIF image ").EndText().RestoreState();
            img = ImageDataFactory.Create(sourceFolder + "manualTransparency_gif.gif");
            canvas.AddImage(img, 100, 300, 200, false);
            canvas.SaveState().BeginText().MoveText(316, 650).SetFontAndSize(PdfFontFactory.CreateFont(StandardFonts.HELVETICA
                                                                                                       ), 16).SetFillColor(ColorConstants.MAGENTA).ShowText("TIF image ").EndText().RestoreState();
            img = ImageDataFactory.Create(sourceFolder + "manualTransparency_tif.tif");
            canvas.AddImage(img, 300, 300, 200, false);
            canvas.Release();
            pdfDocument.Close();
            NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, destinationFolder
                                                                             , "diff_"));
        }
Пример #8
0
        public virtual void PreLayoutTest02()
        {
            String      outFileName = destinationFolder + "preLayoutTest02.pdf";
            String      cmpFileName = sourceFolder + "cmp_preLayoutTest02.pdf";
            PdfDocument pdfDoc      = new PdfDocument(new PdfWriter(outFileName));
            Document    document    = new Document(pdfDoc, PageSize.Default, false);

            document.Add(new Paragraph("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"));
            StringBuilder text = new StringBuilder();

            for (int i = 0; i < 1200; i++)
            {
                text.Append("A very long text is here...");
            }
            Paragraph twoColumnParagraph = new Paragraph();

            twoColumnParagraph.SetNextRenderer(new PreLayoutTest.TwoColumnParagraphRenderer(twoColumnParagraph));
            iText.Layout.Element.Text textElement = new iText.Layout.Element.Text(text.ToString());
            twoColumnParagraph.Add(textElement).SetFont(PdfFontFactory.CreateFont(StandardFonts.HELVETICA));
            document.Add(twoColumnParagraph);
            document.Add(new Paragraph("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"));
            int paragraphLastPageNumber = -1;
            IList <IRenderer> documentChildRenderers = document.GetRenderer().GetChildRenderers();

            for (int i = documentChildRenderers.Count - 1; i >= 0; i--)
            {
                if (documentChildRenderers[i].GetModelElement() == twoColumnParagraph)
                {
                    paragraphLastPageNumber = documentChildRenderers[i].GetOccupiedArea().GetPageNumber();
                    break;
                }
            }
            twoColumnParagraph.SetNextRenderer(new PreLayoutTest.TwoColumnParagraphRenderer(twoColumnParagraph, paragraphLastPageNumber
                                                                                            ));
            document.Relayout();
            //Close document. Drawing of content is happened on close
            document.Close();
            NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, destinationFolder
                                                                             , "diff"));
        }
Пример #9
0
        protected void EmbedFont(String merged, String fontfile, String result)
        {
            // The font file
            FileStream raf = new FileStream(fontfile, FileMode.Open, FileAccess.Read);

            byte[] fontbytes = new byte[(int)raf.Length];
            raf.Read(fontbytes, 0, fontbytes.Length);
            raf.Close();

            // Create a new stream for the font file
            PdfStream stream = new PdfStream(fontbytes);

            stream.SetCompressionLevel(CompressionConstants.DEFAULT_COMPRESSION);
            stream.Put(PdfName.Length1, new PdfNumber(fontbytes.Length));

            PdfDocument pdfDoc             = new PdfDocument(new PdfReader(merged), new PdfWriter(result));
            int         numberOfPdfObjects = pdfDoc.GetNumberOfPdfObjects();

            // Search for the font dictionary
            for (int i = 0; i < numberOfPdfObjects; i++)
            {
                PdfObject pdfObject = pdfDoc.GetPdfObject(i);
                if (pdfObject == null || !pdfObject.IsDictionary())
                {
                    continue;
                }

                PdfDictionary fontDictionary = (PdfDictionary)pdfObject;
                PdfFont       font           = PdfFontFactory.CreateFont(fontfile, PdfEncodings.WINANSI);
                PdfName       fontname       = new PdfName(font.GetFontProgram().GetFontNames().GetFontName());
                if (PdfName.FontDescriptor.Equals(fontDictionary.Get(PdfName.Type)) &&
                    fontname.Equals(fontDictionary.Get(PdfName.FontName)))
                {
                    // Embed the passed font to the pdf document
                    fontDictionary.Put(PdfName.FontFile2, stream.MakeIndirect(pdfDoc).GetIndirectReference());
                }
            }

            pdfDoc.Close();
        }
        protected void ManipulatePdf(String dest)
        {
            PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
            Document    doc    = new Document(pdfDoc);

            // CP1251 encoding type supports russian characters
            PdfFont font = PdfFontFactory.CreateFont(FONT, "Cp1251", true);

            doc.SetFont(font);

            // The text line is "Откуда ты?"
            doc.Add(new Paragraph("\u041e\u0442\u043a\u0443\u0434\u0430 \u0442\u044b?"));

            // The text line is "Увидимся позже. Увидимся."
            doc.Add(new Paragraph("\u0423\u0432\u0438\u0434\u0438\u043c\u0441\u044f "
                                  + "\u043f\u043E\u0437\u0436\u0435. \u0423\u0432\u0438\u0434\u0438\u043c\u0441\u044f."));

            // The text line is "Позвольте мне представиться."
            doc.Add(new Paragraph("\u041f\u043e\u0437\u0432\u043e\u043b\u044c\u0442\u0435 \u043c\u043d\u0435 "
                                  + "\u043f\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u0438\u0442\u044c\u0441\u044f."));

            // The text line is "Это студент."
            doc.Add(new Paragraph("\u042d\u0442\u043e \u0441\u0442\u0443\u0434\u0435\u043d\u0442."));

            // The text line is "Хорошо?"
            doc.Add(new Paragraph("\u0425\u043e\u0440\u043e\u0448\u043e?"));

            // The text line is "Он инженер. Она доктор."
            doc.Add(new Paragraph("\u041e\u043d \u0438\u043d\u0436\u0435\u043d\u0435\u0440. "
                                  + "\u041e\u043d\u0430 \u0434\u043e\u043a\u0442\u043e\u0440."));

            // The text line is "Это окно."
            doc.Add(new Paragraph("\u042d\u0442\u043e \u043e\u043a\u043d\u043e."));

            // The text line is "Повторите, пожалуйста."
            doc.Add(new Paragraph("\u041f\u043e\u0432\u0442\u043e\u0440\u0438\u0442\u0435, "
                                  + "\u043f\u043e\u0436\u0430\u043b\u0443\u0439\u0441\u0442\u0430."));

            doc.Close();
        }
Пример #11
0
        public virtual void StructElemTest07()
        {
            PdfWriter writer = new PdfWriter(destinationFolder + "structElemTest07.pdf");

            writer.SetCompressionLevel(CompressionConstants.NO_COMPRESSION);
            PdfDocument document = new PdfDocument(writer);

            document.SetTagged();
            PdfStructElem doc    = document.GetStructTreeRoot().AddKid(new PdfStructElem(document, PdfName.Document));
            PdfPage       page   = document.AddNewPage();
            PdfCanvas     canvas = new PdfCanvas(page);

            canvas.BeginText();
            canvas.SetFontAndSize(PdfFontFactory.CreateFont(StandardFonts.COURIER), 24);
            canvas.SetTextMatrix(1, 0, 0, 1, 32, 512);
            PdfStructElem paragraph = doc.AddKid(new PdfStructElem(document, PdfName.P));
            PdfStructElem span1     = paragraph.AddKid(new PdfStructElem(document, PdfName.Span, page));

            canvas.OpenTag(new CanvasTag(span1.AddKid(new PdfMcrNumber(page, span1))));
            canvas.ShowText("Hello ");
            canvas.CloseTag();
            PdfStructElem span2 = paragraph.AddKid(new PdfStructElem(document, new PdfName("Chunk"), page));

            canvas.OpenTag(new CanvasTag(span2.AddKid(new PdfMcrNumber(page, span2))));
            canvas.ShowText("World");
            canvas.CloseTag();
            canvas.EndText();
            canvas.Release();
            PdfNamespace @namespace = new PdfNamespace("http://www.w3.org/1999/xhtml");

            span1.SetNamespace(@namespace);
            span1.AddRef(span2);
            span1.SetPhoneticAlphabet(PdfName.ipa);
            span1.SetPhoneme(new PdfString("Heeeelllloooooo"));
            @namespace.AddNamespaceRoleMapping(StandardRoles.SPAN, StandardRoles.SPAN);
            document.GetStructTreeRoot().AddNamespace(@namespace);
            page.Flush();
            document.Close();
            CompareResult("structElemTest07.pdf", "cmp_structElemTest07.pdf", "diff_structElem_07_");
        }
Пример #12
0
        public virtual void Png_imageTransparancy_8bitDepthImage()
        {
            String      outFileName = destinationFolder + "png_imageTransparancy_8bitDepthImage.pdf";
            String      cmpFileName = sourceFolder + "cmp_png_imageTransparancy_8bitDepthImage.pdf";
            PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName, new WriterProperties().SetCompressionLevel
                                                                        (CompressionConstants.NO_COMPRESSION)));
            PdfPage   page   = pdfDocument.AddNewPage(PageSize.A4);
            PdfCanvas canvas = new PdfCanvas(page);

            canvas.SetFillColor(ColorConstants.LIGHT_GRAY).Fill();
            canvas.Rectangle(80, 0, PageSize.A4.GetWidth() - 80, PageSize.A4.GetHeight()).Fill();
            canvas.SaveState().BeginText().MoveText(116, 800).SetFontAndSize(PdfFontFactory.CreateFont(StandardFonts.HELVETICA
                                                                                                       ), 14).SetFillColor(ColorConstants.MAGENTA).ShowText("8 bit depth PNG").MoveText(0, -20).ShowText("This image should not have a black rectangle as background"
                                                                                                                                                                                                         ).EndText().RestoreState();
            ImageData img = ImageDataFactory.Create(sourceFolder + "manualTransparency_8bit.png");

            canvas.AddImage(img, 100, 450, 200, false);
            canvas.Release();
            pdfDocument.Close();
            NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, destinationFolder
                                                                             , "diff_"));
        }
Пример #13
0
 /// <summary>Creates a new BarcodeCodabar.</summary>
 public BarcodeCodabar(PdfDocument document)
     : base(document)
 {
     // 0
     // 1
     // 2
     // 3
     // 4
     // 5
     // 6
     // 7
     // 8
     // 9
     // -
     // $
     // :
     // /
     // .
     // +
     // a
     // b
     // c
     // d
     try {
         x                = 0.8f;
         n                = 2;
         font             = PdfFontFactory.CreateFont(FontConstants.HELVETICA, PdfEncodings.WINANSI);
         size             = 8;
         baseline         = size;
         barHeight        = size * 3;
         textAlignment    = ALIGN_CENTER;
         generateChecksum = false;
         checksumText     = false;
         startStopText    = false;
     }
     catch (Exception e) {
         throw new PdfException(e.Message, e.InnerException);
     }
 }
Пример #14
0
        public virtual void CreatePdf(String dest)
        {
            // Initialize PDF document
            PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
            // Initialize document
            Document  document = new Document(pdf);
            Paragraph p;
            PdfFont   font  = PdfFontFactory.CreateFont(StandardFonts.TIMES_ROMAN);
            Style     style = new Style();

            style.SetBackgroundColor(ColorConstants.YELLOW);
            p = GetNewParagraphInstance().AddStyle(style).SetBorder(new SolidBorder(0.5f)).SetDestination("Top");
            document.Add(p);
            p = GetNewParagraphInstance();
            p.SetBackgroundColor(ColorConstants.GRAY).SetWidth(150).SetHorizontalAlignment(HorizontalAlignment.CENTER).SetTextAlignment
                (TextAlignment.CENTER);
            document.Add(p);
            document.Add(GetNewParagraphInstance().SetRotationAngle(Math.PI / 18));
            document.Add(GetNewParagraphInstance().SetWidth(150).SetHyphenation(new HyphenationConfig("en", "uk", 3, 3
                                                                                                      )));
            document.Add(GetNewParagraphInstance().SetHeight(120).SetVerticalAlignment(VerticalAlignment.BOTTOM).SetBackgroundColor
                             (ColorConstants.YELLOW).SetRelativePosition(10, 10, 50, 10));
            document.Add(GetNewParagraphInstance().SetWidth(UnitValue.CreatePercentValue(80)).SetFont(font).SetFontSize(8).SetFontColor(ColorConstants
                                                                                                                                        .RED));
            document.Add(new AreaBreak());
            document.Add(GetNewParagraphInstance().SetFixedPosition(100, 400, 350).SetAction(PdfAction.CreateGoTo("Top"
                                                                                                                  )));
            document.Add(new AreaBreak());
            document.Add(GetNewParagraphInstance().SetBackgroundColor(ColorConstants.YELLOW).SetMarginBottom(10));
            document.Add(GetNewParagraphInstance().SetBackgroundColor(ColorConstants.LIGHT_GRAY).SetPaddingLeft(20).SetPaddingRight
                             (50));
            document.Add(GetNewParagraphInstance().SetBackgroundColor(ColorConstants.YELLOW));
            document.Add(GetNewParagraphInstance().SetBackgroundColor(ColorConstants.LIGHT_GRAY));
            document.Add(GetNewParagraphInstance().SetBackgroundColor(ColorConstants.YELLOW));
            document.Add(GetNewParagraphInstance().SetBackgroundColor(ColorConstants.LIGHT_GRAY).SetMargin(50).SetPadding(30));
            document.Add(GetNewParagraphInstance().SetBackgroundColor(ColorConstants.YELLOW));
            document.Add(GetNewParagraphInstance().SetBackgroundColor(ColorConstants.LIGHT_GRAY));
            document.Close();
        }
Пример #15
0
        public virtual void FormFieldTest04()
        {
            String      filename = destinationFolder + "formFieldTest04.pdf";
            PdfDocument pdfDoc   = new PdfDocument(new PdfReader(sourceFolder + "formFieldFile.pdf"), new PdfWriter(filename
                                                                                                                    ));
            PdfAcroForm      form  = PdfAcroForm.GetAcroForm(pdfDoc, true);
            PdfPage          page  = pdfDoc.GetFirstPage();
            Rectangle        rect  = new Rectangle(210, 490, 150, 22);
            PdfTextFormField field = PdfFormField.CreateText(pdfDoc, rect, "TestField", "some value in courier font",
                                                             PdfFontFactory.CreateFont(StandardFonts.COURIER), 10);

            form.AddField(field, page);
            pdfDoc.Close();
            CompareTool compareTool  = new CompareTool();
            String      errorMessage = compareTool.CompareByContent(filename, sourceFolder + "cmp_formFieldTest04.pdf", destinationFolder
                                                                    , "diff_");

            if (errorMessage != null)
            {
                NUnit.Framework.Assert.Fail(errorMessage);
            }
        }
Пример #16
0
        public static Cell getNormalCell(String input, float size, int rowSpan = 1, int colSpan = 1)
        {
            if (String.IsNullOrEmpty(input))
            {
                return(new Cell(rowSpan, colSpan));
            }

            PdfFont f = PdfFontFactory.CreateFont(FontConstants.HELVETICA);

            Cell cell = new Cell(rowSpan, colSpan).Add(new Paragraph(input).SetFont(f));

            cell.SetHorizontalAlignment(HorizontalAlignment.LEFT);
            if (size > 0)
            {
                //size = -size;
                cell.SetFontSize(size);
                cell.SetFontColor(Color.BLACK);
            }
            // cell.SetNextRenderer(new RoundedCornersCellRenderer(cell));
            cell.SetBorder(Border.NO_BORDER);
            return(cell);
        }
Пример #17
0
        private void ManipulatePdf(String dest)
        {
            PdfFont font = PdfFontFactory.CreateFont(FONT, PdfEncodings.IDENTITY_H);

            FileStream fileStream = new FileStream("../../../resources/data/sRGB_CS_profile.icm",
                                                   FileMode.Open, FileAccess.Read);

            PdfADocument pdfDoc = new PdfADocument(new PdfWriter(dest), PdfAConformanceLevel.PDF_A_2A,
                                                   new PdfOutputIntent("Custom", "",
                                                                       null, "sRGB IEC61966-2.1", fileStream));

            Document document = new Document(pdfDoc);

            // Specifies that document should contain tag structure
            pdfDoc.SetTagged();
            pdfDoc.GetCatalog().SetLang(new PdfString("en-us"));

            Paragraph p = new Paragraph("Hello World!").SetFont(font).SetFontSize(10);

            document.Add(p);
            document.Close();
        }
Пример #18
0
        public virtual void WordSpacingTest01()
        {
            String      outFileName = destinationFolder + "wordSpacingTest01.pdf";
            String      cmpFileName = sourceFolder + "cmp_wordSpacingTest01.pdf";
            PdfDocument pdfDocument = new PdfDocument(new PdfWriter(new FileStream(outFileName, FileMode.Create)));
            Document    document    = new Document(pdfDocument);
            PdfFont     font        = PdfFontFactory.CreateFont(FontConstants.HELVETICA);
            Paragraph   p           = new Paragraph().SetFont(font);

            p.Add("Video provides a powerful way to help you prove your point. When you click Online Video, you can paste in the embed code for the video you want to add. You can also type a keyword to search online for the video that best fits your document.\n"
                  + "To make your document look professionally produced, Word provides header, footer, cover page, and text box designs that complement each other. For example, you can add a matching cover page, header, and sidebar. Click Insert and then choose the elements you want from the different galleries.\n"
                  + "Themes and styles also help keep your document coordinated. When you click Design and choose a new Theme, the pictures, charts, and SmartArt graphics change to match your new theme. When you apply styles, your headings change to match the new theme.\n"
                  + "Save time in Word with new buttons that show up where you need them. To change the way a picture fits in your document, click it and a button for layout options appears next to it. When you work on a table, click where you want to add a row or a column, and then click the plus sign.\n"
                  + "Reading is easier, too, in the new Reading view. You can collapse parts of the document and focus on the text you want. If you need to stop reading before you reach the end, Word remembers where you left off - even on another device. "
                  );
            p.Add(new Text("You can collapse parts of the document and focus.").SetBackgroundColor(DeviceRgb.GREEN));
            p.SetWordSpacing(15);
            document.Add(p);
            document.Close();
            NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, destinationFolder
                                                                             , "diff"));
        }
Пример #19
0
        public virtual void CreatePdf(String dest)
        {
            PdfDocument pdf      = new PdfDocument(new PdfWriter(dest));
            Document    document = new Document(pdf);
            Style       normal   = new Style();
            PdfFont     font     = PdfFontFactory.CreateFont(StandardFonts.TIMES_ROMAN);

            normal.SetFont(font).SetFontSize(14);
            Style   code      = new Style();
            PdfFont monospace = PdfFontFactory.CreateFont(StandardFonts.COURIER);

            code.SetFont(monospace).SetFontColor(ColorConstants.RED).SetBackgroundColor(ColorConstants.LIGHT_GRAY);
            Paragraph p = new Paragraph();

            p.Add(new Text("The Strange Case of ").AddStyle(normal));
            p.Add(new Text("Dr. Jekyll").AddStyle(code));
            p.Add(new Text(" and ").AddStyle(normal));
            p.Add(new Text("Mr. Hyde").AddStyle(code));
            p.Add(new Text(".").AddStyle(normal));
            document.Add(p);
            document.Close();
        }
Пример #20
0
        public virtual void DisabledVisibilityPolicyAllOffTest()
        {
            String      srcPdf  = "sourceWithDifferentLayers.pdf";
            String      destPdf = "disabledVisibilityPolicyAllOffTest.pdf";
            String      cmpPdf  = "cmp_" + destPdf;
            PdfDocument pdfDoc  = new PdfDocument(new PdfReader(sourceFolder + srcPdf), new PdfWriter(destinationFolder
                                                                                                      + destPdf));
            PdfCanvas canvas = new PdfCanvas(pdfDoc.GetFirstPage());

            canvas.SetFontAndSize(PdfFontFactory.CreateFont(StandardFonts.HELVETICA), 18);
            IList <PdfLayer>   allLayers             = pdfDoc.GetCatalog().GetOCProperties(true).GetLayers();
            PdfLayerMembership layerMembershipAllOff = new PdfLayerMembership(pdfDoc);

            layerMembershipAllOff.AddLayer(allLayers[0]);
            layerMembershipAllOff.AddLayer(allLayers[1]);
            layerMembershipAllOff.SetVisibilityPolicy(PdfName.AllOff);
            PdfLayerTestUtils.AddTextInsideLayer(layerMembershipAllOff, canvas, "visibilityPolicyAllOffTest", 200, 500
                                                 );
            pdfDoc.Close();
            NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(destinationFolder + destPdf, sourceFolder
                                                                             + cmpPdf, destinationFolder));
        }
        public virtual void NotoSerifWithInvalidXYPlacementAnchorDeltaTest()
        {
            String      outPdf = destinationFolder + "notoSerifWithInvalidXYPlacementAnchorDeltaTest.pdf";
            String      cmpPdf = sourceFolder + "cmp_notoSerifWithInvalidXYPlacementAnchorDeltaTest.pdf";
            PdfDocument pdfDoc = new PdfDocument(new PdfWriter(outPdf));
            PdfPage     page   = pdfDoc.AddNewPage();
            PdfFont     font   = PdfFontFactory.CreateFont(fontsFolder + "NotoSerif-Regular_v1.7.ttf", PdfEncodings.IDENTITY_H
                                                           );
            // ゙B̸̭̼ͣ̎̇
            IList <Glyph> glyphs = JavaUtil.ArraysAsList(font.GetGlyph((int)'\u0042'), ApplyGlyphParameters('\u0363', -
                                                                                                            1, 327, 178, font), ApplyGlyphParameters('\u030e', -1, 10, 298, font), ApplyGlyphParameters('\u0307',
                                                                                                                                                                                                        -1, 0, 224, font), ApplyGlyphParameters('\u032d', -3, 11, 620, font), ApplyGlyphParameters('\u033c', -
                                                                                                                                                                                                                                                                                                   1, -1, -220, font), font.GetGlyph((int)'\u0338'));
            GlyphLine glyphLine = new GlyphLine(glyphs);
            PdfCanvas canvas    = new PdfCanvas(page);

            canvas.SaveState().BeginText().MoveText(36, 800).SetFontAndSize(font, 12).ShowText(glyphLine).EndText().RestoreState
                ();
            canvas.Release();
            pdfDoc.Close();
            NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outPdf, cmpPdf, destinationFolder));
        }
Пример #22
0
        private void CreateWrapper(String encryptedName, String wrapperName, String cryptoFilter)
        {
            String      inPath   = sourceFolder + "cmp_" + encryptedName;
            String      cmpPath  = sourceFolder + "cmp_" + wrapperName;
            String      outPath  = destinationFolder + wrapperName;
            String      diff     = "diff_" + wrapperName + "_";
            PdfDocument document = new PdfDocument(new PdfWriter(outPath, new WriterProperties().SetPdfVersion(PdfVersion
                                                                                                               .PDF_2_0)));
            PdfFileSpec fs = PdfEncryptedPayloadFileSpecFactory.Create(document, inPath, new PdfEncryptedPayload(cryptoFilter
                                                                                                                 ));

            document.SetEncryptedPayload(fs);
            PdfFont   font   = PdfFontFactory.CreateFont();
            PdfCanvas canvas = new PdfCanvas(document.AddNewPage());

            canvas.SaveState().BeginText().MoveText(36, 750).SetFontAndSize(font, 30).ShowText("Hi! I'm wrapper document."
                                                                                               ).EndText().RestoreState();
            canvas.Release();
            document.Close();
            NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outPath, cmpPath, destinationFolder, diff
                                                                             ));
        }
        public virtual void FileSpecCheckTest03()
        {
            PdfWriter       writer       = new PdfWriter(new MemoryStream());
            Stream          @is          = new FileStream(sourceFolder + "sRGB Color Space Profile.icm", FileMode.Open, FileAccess.Read);
            PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1"
                                                               , @is);
            PdfADocument pdfDocument = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, outputIntent);
            PdfPage      page        = pdfDocument.AddNewPage();
            PdfFont      font        = PdfFontFactory.CreateFont(sourceFolder + "FreeSans.ttf", "WinAnsi", true);
            PdfCanvas    canvas      = new PdfCanvas(page);

            canvas.SaveState().BeginText().MoveText(36, 700).SetFontAndSize(font, 36).ShowText("Hello World!").EndText
                ().RestoreState();
            MemoryStream txt  = new MemoryStream();
            StreamWriter @out = new StreamWriter(txt);

            @out.Write("<foo><foo2>Hello world</foo2></foo>");
            @out.Dispose();
            pdfDocument.AddFileAttachment("foo file", PdfFileSpec.CreateEmbeddedFileSpec(pdfDocument, txt.ToArray(), "foo file"
                                                                                         , "foo.xml", PdfName.ApplicationXml, null, PdfName.Source));
            pdfDocument.Close();
        }
Пример #24
0
        public PdfFont GetPdfFont(string fontname)
        {
            if (fontname == null)
            {
                fontname = "";
            }
            switch (fontname.ToUpper())
            {
            case "HELVETICA":
                return(PdfFontFactory.CreateFont(StandardFonts.HELVETICA));

            case "HELVETICA_BOLD":
                return(PdfFontFactory.CreateFont(StandardFonts.HELVETICA_BOLD));

            case "TIMES_ROMAN":
                return(PdfFontFactory.CreateFont(StandardFonts.TIMES_ROMAN));

            case "COURIER":
                return(PdfFontFactory.CreateFont(StandardFonts.COURIER));

            case "COURIER_BOLD":
                return(PdfFontFactory.CreateFont(StandardFonts.COURIER_BOLD));

            case "COURIER_BOLDOBLIQUE":
                return(PdfFontFactory.CreateFont(StandardFonts.COURIER_BOLDOBLIQUE));

            case "TIMES_BOLDITALIC":
                return(PdfFontFactory.CreateFont(StandardFonts.TIMES_BOLDITALIC));

            case "TIMES_ITALIC":
                return(PdfFontFactory.CreateFont(StandardFonts.TIMES_ITALIC));

            case "SYMBOL":
                return(PdfFontFactory.CreateFont(StandardFonts.SYMBOL));

            default:
                return(PdfFontFactory.CreateFont(StandardFonts.HELVETICA));
            }
        }
Пример #25
0
        private static void AddContentToPage(PdfPage pdfPage, PdfFont font, PdfImageXObject xObject)
        {
            PdfCanvas canvas = AddBasicContent(pdfPage, font);

            canvas.SaveState().Rectangle(250, 500, 100, 100).Fill().RestoreState();
            PdfFont courier = PdfFontFactory.CreateFont(StandardFonts.COURIER);

            courier.MakeIndirect(pdfPage.GetDocument());
            canvas.SaveState().BeginText().MoveText(36, 650).SetFontAndSize(courier, 16).ShowText("Hello Courier!").EndText
                ().RestoreState();
            canvas.SaveState().Circle(100, 400, 25).Fill().RestoreState();
            canvas.SaveState().RoundRectangle(100, 650, 100, 100, 10).Fill().RestoreState();
            canvas.SaveState().SetLineWidth(10).RoundRectangle(250, 650, 100, 100, 10).Stroke().RestoreState();
            canvas.SaveState().SetLineWidth(5).Arc(400, 650, 550, 750, 0, 180).Stroke().RestoreState();
            canvas.SaveState().SetLineWidth(5).MoveTo(400, 550).CurveTo(500, 570, 450, 450, 550, 550).Stroke().RestoreState
                ();
            canvas.AddXObject(xObject, 100, 500, 400);
            PdfImageXObject xObject2 = new PdfImageXObject(ImageDataFactory.Create(sourceFolder + "itext.png"));

            xObject2.MakeIndirect(pdfPage.GetDocument());
            canvas.AddXObject(xObject2, 100, 300, 400);
        }
Пример #26
0
        /// <exception cref="System.Exception"/>
        private byte[] CreatePdfWithRotatedXObject(String xobjectText)
        {
            MemoryStream baos        = new MemoryStream();
            PdfDocument  pdfDocument = new PdfDocument(new PdfWriter(baos).SetCompressionLevel(0));
            Document     document    = new Document(pdfDocument);

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

            canvas.SetStrokeColor(Color.GREEN).Rectangle(0, 0, template.GetWidth(), template.GetHeight()).Stroke();
            AffineTransform tx = new AffineTransform();

            tx.Translate(0, template.GetHeight());
            tx.Rotate((float)(-90 / 180f * Math.PI));
            canvas.ConcatMatrix(tx).BeginText().SetFontAndSize(PdfFontFactory.CreateFont(FontConstants.HELVETICA), 12)
            .MoveText(0, template.GetWidth() - 12).ShowText(xobjectText).EndText();
            document.Add(new Image(template).SetRotationAngle(Math.PI / 2)).Add(new Paragraph("C"));
            document.Close();
            return(baos.ToArray());
        }
Пример #27
0
        public virtual void TagStructureRemovingTest03()
        {
            PdfWriter writer = new PdfWriter(destinationFolder + "tagStructureRemovingTest03.pdf");

            writer.SetCompressionLevel(CompressionConstants.NO_COMPRESSION);
            PdfDocument document = new PdfDocument(writer);

            document.SetTagged();
            PdfPage        page       = document.AddNewPage();
            TagTreePointer tagPointer = new TagTreePointer(document);

            tagPointer.SetPageForTagging(page);
            PdfCanvas canvas = new PdfCanvas(page);

            tagPointer.AddTag(StandardRoles.P);
            WaitingTagsManager waitingTagsManager = tagPointer.GetContext().GetWaitingTagsManager();
            Object             pWaitingTagObj     = new Object();

            waitingTagsManager.AssignWaitingState(tagPointer, pWaitingTagObj);
            PdfFont standardFont = PdfFontFactory.CreateFont(StandardFonts.COURIER);

            canvas.BeginText().SetFontAndSize(standardFont, 24).SetTextMatrix(1, 0, 0, 1, 32, 512);
            tagPointer.AddTag(StandardRoles.SPAN);
            canvas.OpenTag(tagPointer.GetTagReference()).ShowText("Hello ").CloseTag();
            canvas.SetFontAndSize(standardFont, 30).OpenTag(tagPointer.GetTagReference()).ShowText("World").CloseTag()
            .EndText();
            tagPointer.MoveToParent().MoveToParent();
            document.RemovePage(1);
            PdfPage newPage = document.AddNewPage();

            canvas = new PdfCanvas(newPage);
            tagPointer.SetPageForTagging(newPage);
            waitingTagsManager.TryMovePointerToWaitingTag(tagPointer, pWaitingTagObj);
            tagPointer.AddTag(StandardRoles.SPAN);
            canvas.OpenTag(tagPointer.GetTagReference()).BeginText().SetFontAndSize(standardFont, 24).SetTextMatrix(1,
                                                                                                                    0, 0, 1, 32, 512).ShowText("Hello.").EndText().CloseTag();
            document.Close();
            CompareResult("tagStructureRemovingTest03.pdf", "cmp_tagStructureRemovingTest03.pdf", "diffRemoving03_");
        }
        public virtual void PdfA1DocWithPdfA1ListFieldTest()
        {
            String  name         = "pdfA1DocWithPdfA1ListField";
            String  fileName     = destinationFolder + name + ".pdf";
            String  cmp          = sourceFolder + "cmp/PdfAFormFieldTest/cmp_pdfA1DocWithPdfA1ListField.pdf";
            PdfFont fontFreeSans = PdfFontFactory.CreateFont(sourceFolder + "FreeSans.ttf", "WinAnsi", true);
            Stream  @is          = new FileStream(sourceFolder + "sRGB Color Space Profile.icm", FileMode.Open, FileAccess.Read);
            PdfAConformanceLevel conformanceLevel = PdfAConformanceLevel.PDF_A_1B;
            PdfADocument         pdfDoc           = new PdfADocument(new PdfWriter(fileName), conformanceLevel, new PdfOutputIntent("Custom"
                                                                                                                                    , "", "http://www.color.org", "sRGB IEC61966-2.1", @is));
            PdfAcroForm        form = PdfAcroForm.GetAcroForm(pdfDoc, true);
            PdfChoiceFormField f    = PdfFormField.CreateList(pdfDoc, new Rectangle(86, 556, 50, 200), "list", "9", new String
                                                              [] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" }, fontFreeSans, conformanceLevel);

            f.SetValue("4");
            f.SetTopIndex(2);
            f.SetListSelected(new String[] { "3", "5" });
            form.AddField(f);
            pdfDoc.Close();
            NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(fileName, cmp, destinationFolder));
            NUnit.Framework.Assert.IsNull(new VeraPdfValidator().Validate(fileName));
        }
Пример #29
0
        public virtual void CreatePdf(String dest, RecordListViewModel records)
        {
            //Initialize PDF writer
            PdfWriter writer = new PdfWriter(dest);
            //Initialize PDF document
            PdfDocument pdf = new PdfDocument(writer);
            // Initialize document
            Document document = new Document(pdf);
            // Create a PdfFont
            PdfFont font = PdfFontFactory.CreateFont(iText.IO.Font.Constants.StandardFonts.TIMES_ROMAN);

            // Add a Paragraph
            document.Add(new Paragraph("Record report").SetFont(font).SetFontSize(18).SetTextAlignment(TextAlignment.CENTER));
            // Add ListItem objects
            float[] columnWidths = { 2, 2, 2, 5, 2, 4 };
            Table   table        = new Table(columnWidths, true);

            table.SetFontSize(11);
            table.AddCell("Record ID");
            table.AddCell("Project Name");
            table.AddCell("Task Name");
            table.AddCell("Note");
            table.AddCell("Work time");
            table.AddCell("Start date and time");
            foreach (var record in records.Records)
            {
                table.AddCell(record.Id.ToString());
                table.AddCell(record.ProjectName);
                table.AddCell(record.TaskName.ToString());
                table.AddCell(record.Note);
                table.AddCell(record.Hours.ToString());
                table.AddCell(record.RecordDateTime.ToString());
            }
            table.SetBorder(new SolidBorder(1));
            document.Add(table);

            //Close document
            document.Close();
        }
Пример #30
0
        private void Fill_Open_pdf_Button_Click(object sender, RoutedEventArgs e)
        {
            // temp save document and open
            var filePath = System.Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);

            filePath = Path.Combine(filePath, "Fill-A-Doc");
            System.IO.Directory.CreateDirectory(filePath);
            DEST = filePath + "\\temp.pdf";;

            PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(DEST));
            PdfAcroForm form   = PdfAcroForm.GetAcroForm(pdfDoc, true);

            try
            {
                form.SetGenerateAppearance(true);

                PdfFont font = PdfFontFactory.CreateFont();

                IEnumerable <TextBox> elements = FindVisualChildren <TextBox>(lbFormFields).Where(x => x.Tag != null && x.Tag.ToString() == "textBox_FieldValue");
                foreach (TextBox tb in elements)
                {
                    String FieldName = ((Grid)tb.Parent).Tag.ToString();
                    IEnumerable <TextBox> fontSizeTextBoxElements = FindVisualChildren <TextBox>(tb.Parent).Where(x => x.Tag != null && x.Tag.ToString() == FieldName);
                    float fieldFontSize = 10f;
                    float.TryParse(fontSizeTextBoxElements.First().Text, out fieldFontSize);
                    form.GetField(FieldName).SetValue(tb.Text, font, fieldFontSize);
                }

                System.Diagnostics.Process.Start(DEST);
            }
            catch
            {
                MessageBox.Show("An error occurred!");
            }
            finally
            {
                pdfDoc.Close();
            }
        }