コード例 #1
0
ファイル: PdfPageSize.cs プロジェクト: changhuixu/PdfExamples
        public static void Create(string dest)
        {
            const float in2mm     = 72f / 25.4f;
            var         colorOrig = Color.Red;
            var         colorNew  = Color.Blue;
            var         doc       = new GcPdfDocument();
            // The default page size is Letter (8 1/2" x 11") with portrait orientation:
            var page          = doc.NewPage();
            var sOrigPageInfo = $"Original page size: {page.Size} pts ({page.Size.Width / 72f}\" * {page.Size.Height / 72f}\"),\r\npaper kind: {page.PaperKind}, landscape: {page.Landscape}.";
            // Save original page bounds:
            var rOrig = page.Bounds;

            // Change page parameters:
            page.Landscape = true;
            page.PaperKind = PaperKind.A4;
            var sNewPageInfo = $"New page size: {page.Size} pts ({page.Size.Width / in2mm}mm * {page.Size.Height / in2mm}mm),\r\npaper kind: {page.PaperKind}, landscape: {page.Landscape}.";
            // New page bounds:
            var rNew = page.Bounds;

            // Draw original and new page bounds:
            page.Graphics.DrawRectangle(rOrig, colorOrig, 6);
            page.Graphics.DrawRectangle(rNew, colorNew, 6);
            // Draw original and new page infos:
            TextFormat tf = new TextFormat();

            tf.Font      = StandardFonts.Times;
            tf.FontSize  = 14;
            tf.ForeColor = colorOrig;
            page.Graphics.DrawString(sOrigPageInfo, tf, new PointF(72, 72));
            tf.ForeColor = colorNew;
            page.Graphics.DrawString(sNewPageInfo, tf, new PointF(72, 72 * 2));
            // Done:
            doc.Save(dest);
        }
コード例 #2
0
ファイル: ShippingLabels.cs プロジェクト: GrapeCity/GcPdf
        // The main sample driver.
        public void CreatePDF(Stream stream)
        {
            GcPdfDocument doc = new GcPdfDocument();

            Init(doc);

            // Loop over clients, print up to 4 labels per page:
            int i = 0;

            for (int pg = 0; pg < (s_clients.Count + 3) / 4; ++pg)
            {
                Page page = doc.NewPage();
                PrintLabel(s_clients[i++], page, new RectangleF(hmargin, vmargin, _labelWidth, _labelHeight));
                if (i < s_clients.Count)
                {
                    PrintLabel(s_clients[i++], page, new RectangleF(hmargin + _labelWidth, vmargin, _labelWidth, _labelHeight));
                }
                if (i < s_clients.Count)
                {
                    PrintLabel(s_clients[i++], page, new RectangleF(hmargin, vmargin + _labelHeight, _labelWidth, _labelHeight));
                }
                if (i < s_clients.Count)
                {
                    PrintLabel(s_clients[i++], page, new RectangleF(hmargin + _labelWidth, vmargin + _labelHeight, _labelWidth, _labelHeight));
                }
            }
            // Done:
            doc.Save(stream);
            Term();
        }
コード例 #3
0
ファイル: RemoveSignatures.cs プロジェクト: GrapeCity/GcPdf
        public int CreatePDF(Stream stream)
        {
            var doc = new GcPdfDocument();

            using (var fs = new FileStream(Path.Combine("Resources", "PDFs", "TimeSheet.pdf"), FileMode.Open, FileAccess.Read))
            {
                doc.Load(fs);

                // Fields can be children of other fields, so we use
                // a recursive method to iterate through the whole tree:
                removeSignatures(doc.AcroForm.Fields);

                // Done:
                doc.Save(stream);
                return(doc.Pages.Count);

                void removeSignatures(FieldCollection fields)
                {
                    foreach (var f in fields)
                    {
                        if (f is SignatureField sf)
                        {
                            sf.Value = null;
                        }
                        removeSignatures(f.Children);
                    }
                }
            }
        }
コード例 #4
0
ファイル: DDPdf.cs プロジェクト: GrapeCityJP/DioDocsSamples
        public static void Create(string platformname)
        {
            // トライアル用
            string key = Resources.ResourceManager.GetString("DdPdfLicenseString");

            GcPdfDocument.SetLicenseKey(key);

            // PDFドキュメントを作成します。
            GcPdfDocument doc = new GcPdfDocument();

            // ページを追加し、そのグラフィックスを取得します。
            GcPdfGraphics g = doc.NewPage().Graphics;

            // ページに文字列を描画します。
            g.DrawString("Hello, de:code 2019!" + Environment.NewLine + "from " + platformname,
                         new TextFormat()
            {
                Font = StandardFonts.Helvetica, FontSize = 12
            },
                         new PointF(72, 72));

            // メモリストリームに保存
            MemoryStream ms = new MemoryStream();

            doc.Save(ms, false);
            ms.Seek(0, SeekOrigin.Begin);

            // BLOBストレージにアップロード
            AzStorage.UploadPdfAsync(ms);
        }
コード例 #5
0
        static void Main(string[] args)
        {
            Console.WriteLine("DioDocs for PDF. PDF Form Data Import! (ImportFormDataFromCollection)");

            // PDFフォームへ入力するデータ
            var kvp = new KeyValuePair <string, IList <string> >[]
            {
                new KeyValuePair <string, IList <string> >("氏名", new string[] { "葡萄城 太郎" }),
                new KeyValuePair <string, IList <string> >("会社名", new string[] { "ディオドック株式会社" }),
                new KeyValuePair <string, IList <string> >("フリガナ", new string[] { "ブドウジョウ タロウ" }),
                new KeyValuePair <string, IList <string> >("TEL", new string[] { "022-777-8888" }),
                new KeyValuePair <string, IList <string> >("部署名", new string[] { "ピノタージュ" }),
                new KeyValuePair <string, IList <string> >("住所", new string[] { "M県S市広瀬区花京院3-1-4" }),
                new KeyValuePair <string, IList <string> >("郵便番号", new string[] { "981-9999" }),
                new KeyValuePair <string, IList <string> >("Email", new string[] { "*****@*****.**" })
            };

            var doc = new GcPdfDocument();

            // PDFを読み込み
            doc.Load(new FileStream("grapecity_order_template.pdf", FileMode.Open, FileAccess.Read));

            // KeyValuePairからデータを入力
            doc.ImportFormDataFromCollection(kvp);

            // PDFを保存
            doc.Save("grapecity_order_embed.pdf");
        }
コード例 #6
0
        public int CreatePDF(Stream stream)
        {
            GcPdfDocument doc = new GcPdfDocument();

            using (var fs0 = new FileStream(Path.Combine("Resources", "PDFs", "The-Rich-History-of-JavaScript.pdf"), FileMode.Open, FileAccess.Read))
                using (var fs1 = new FileStream(Path.Combine("Resources", "PDFs", "CompleteJavaScriptBook.pdf"), FileMode.Open, FileAccess.Read))
                {
                    doc.Load(fs0);
                    // Save page count for the navigaion link added below:
                    var pgNo = doc.Pages.Count;
                    var doc1 = new GcPdfDocument();
                    doc1.Load(fs1);
                    doc.MergeWithDocument(doc1, new MergeDocumentOptions());

                    // Insert a note at the beginning of the document:
                    var page = doc.Pages.Insert(0);
                    var rc   = Common.Util.AddNote(
                        "GcPdfDocument.MergeWithDocument() method allows to add to the current document all or some pages " +
                        "from another document.\n" +
                        "In this sample we load one PDF, append another whole PDF to it, and save the result.\n" +
                        "Click this note to jump directly to the first page of the 2nd document.",
                        page);

                    // Link the note to the first page of the second document:
                    page.Annotations.Add(new LinkAnnotation(rc, new DestinationFit(pgNo + 1)));
                    // Done (target document must be saved BEFORE the source is disposed):
                    doc.Save(stream);
                }
            return(doc.Pages.Count);
        }
コード例 #7
0
        public void CreatePDF(Stream stream)
        {
            var doc = new GcPdfDocument();
            var g   = doc.NewPage().Graphics;
            ActionJavaScript jsAction = new ActionJavaScript(js);
            TextFormat       tf       = new TextFormat()
            {
                Font     = StandardFonts.Times,
                FontSize = 14
            };
            // Draw the link string in a rectangle:
            var text = "Click this to show the popup menu.";
            var rect = new RectangleF(new PointF(72, 72), g.MeasureString(text, tf));

            g.FillRectangle(rect, Color.LightGoldenrodYellow);
            g.DrawString(text, tf, rect);
            var result = new LinkAnnotation(rect, jsAction);

            doc.Pages.Last.Annotations.Add(result);
            // Add warning about this possibly not working in a browser:
            Common.Util.AddNote(
                "Note that JavaScript may not work in some PDF viewers such as built-in browser viewers.",
                doc.Pages.Last, new RectangleF(rect.X, rect.Bottom + 36, 400, 400));
            // Done:
            doc.Save(stream);
        }
コード例 #8
0
        public void CreatePDF(Stream stream)
        {
            // Number of pages to generate:
            const int N   = 5000;
            var       doc = new GcPdfDocument();

            // To create a linearized PDF, the only thing we need to do is raise a flag:
            doc.Linearized = true;
            // Prep a TextLayout to hold/format the text:
            var page = doc.NewPage();
            var tl   = page.Graphics.CreateTextLayout();

            tl.DefaultFormat.Font     = StandardFonts.Times;
            tl.DefaultFormat.FontSize = 12;
            // Use TextLayout to layout the whole page including margins:
            tl.MaxHeight       = page.Size.Height;
            tl.MaxWidth        = page.Size.Width;
            tl.MarginAll       = 72;
            tl.FirstLineIndent = 72 / 2;
            // Generate the document:
            for (int pageIdx = 0; pageIdx < N; ++pageIdx)
            {
                // Note: for the sake of this sample, we do not care if a sample text does not fit on a page.
                tl.Append(Common.Util.LoremIpsum(2));
                tl.PerformLayout(true);
                doc.Pages.Last.Graphics.DrawTextLayout(tl, PointF.Empty);
                if (pageIdx < N - 1)
                {
                    doc.Pages.Add();
                    tl.Clear();
                }
            }
            // Done:
            doc.Save(stream);
        }
コード例 #9
0
        public void CreatePDF(Stream stream)
        {
            var doc = new GcPdfDocument();
            var g   = doc.NewPage().Graphics;
            //
            var font = Font.FromFile(Path.Combine("Resources", "Fonts", "Gabriola.ttf"));
            var tf   = new TextFormat()
            {
                Font = font, FontSize = 20
            };
            //
            var tl = g.CreateTextLayout();

            tl.AppendLine("Line with no custom font features.", tf);
            //
            tf.FontFeatures = new FontFeature[] { new FontFeature(FeatureTag.ss03) };
            tl.AppendLine("Line with font feature ss03 enabled.", tf);
            //
            tf.FontFeatures = new FontFeature[] { new FontFeature(FeatureTag.ss05) };
            tl.AppendLine("Line with font feature ss05 enabled.", tf);
            //
            tf.FontFeatures = new FontFeature[] { new FontFeature(FeatureTag.ss07) };
            tl.AppendLine("Line with font feature ss07 enabled.", tf);
            //
            tl.PerformLayout(true);
            g.DrawTextLayout(tl, new PointF(72, 72));
            // Done:
            doc.Save(stream);
        }
コード例 #10
0
        public void CreatePDF(Stream stream)
        {
            Font gabriola = Font.FromFile(Path.Combine("Resources", "Fonts", "Gabriola.ttf"));

            if (gabriola == null)
            {
                throw new Exception("Could not load font Gabriola");
            }

            // Now that we have our font, use it to render some text:
            TextFormat tf = new TextFormat()
            {
                Font = gabriola, FontSize = 16
            };
            GcPdfDocument doc = new GcPdfDocument();
            GcPdfGraphics g   = doc.NewPage().Graphics;

            g.DrawString($"Sample text drawn with font {gabriola.FontFamilyName}.", tf, new PointF(72, 72));
            // We can change the font size:
            tf.FontSize += 4;
            g.DrawString("The quick brown fox jumps over the lazy dog.", tf, new PointF(72, 72 * 2));
            // We can force GcPdf to emulate bold or italic style with a non-bold (non-italic) font, e.g.:
            tf.FontStyle = FontStyle.Bold;
            g.DrawString("This line prints with the same font, using emulated bold style.", tf, new PointF(72, 72 * 3));
            // But of course rather than emulated, it is much better to use real bold/italic fonts.
            // So finally, get a real bold italic font and print a line with it:
            Font timesbi = Font.FromFile(Path.Combine("Resources", "Fonts", "timesbi.ttf"));

            tf.Font      = timesbi ?? throw new Exception("Could not load font timesbi");
            tf.FontStyle = FontStyle.Regular;
            g.DrawString($"This line prints with {timesbi.FullFontName}.", tf, new PointF(72, 72 * 4));
            // Done:
            doc.Save(stream);
        }
コード例 #11
0
ファイル: RedactArea.cs プロジェクト: GrapeCity/GcPdf
        public int CreatePDF(Stream stream)
        {
            var doc = new GcPdfDocument();

            using (var fs = new FileStream(Path.Combine("Resources", "PDFs", "SlidePages.pdf"), FileMode.Open, FileAccess.Read))
            {
                // Load the PDF containing redact annotations (areas marked for redaction):
                doc.Load(fs);

                var rc = new RectangleF(16, 16, 280, 300);

                var redact = new RedactAnnotation()
                {
                    Rect             = rc,
                    Page             = doc.Pages[0],
                    OverlayText      = "This content has been redacted.",
                    OverlayFillColor = Color.PaleGoldenrod
                };

                // Apply the redact:
                doc.Redact(redact);

                // doc.Pages[0].Graphics.DrawRectangle(rc, Color.Red);

                // Done:
                doc.Save(stream);
                return(doc.Pages.Count);
            }
        }
コード例 #12
0
        public void CreatePDF(Stream stream)
        {
            // Rotation angle, degrees clockwise:
            float angle = -45;
            //
            var doc = new GcPdfDocument();
            var g   = doc.NewPage().Graphics;
            // Create a text layout, pick a font and font size:
            TextLayout tl = g.CreateTextLayout();

            tl.DefaultFormat.Font     = StandardFonts.Times;
            tl.DefaultFormat.FontSize = 24;
            // Add a text, and perform layout:
            tl.Append("Rotated text.");
            tl.PerformLayout(true);
            // Text insertion point at (1",1"):
            var ip = new PointF(72, 72);
            // Now that we have text size, create text rectangle with top left at insertion point:
            var rect = new RectangleF(ip.X, ip.Y, tl.ContentWidth, tl.ContentHeight);

            // Rotate the text around its bounding rect's center:
            // we now have the text size, and can rotate it about its center:
            g.Transform = Matrix3x2.CreateRotation((float)(angle * Math.PI) / 180f, new Vector2(ip.X + tl.ContentWidth / 2, ip.Y + tl.ContentHeight / 2));
            // Draw rotated text and bounding rectangle:
            g.DrawTextLayout(tl, ip);
            g.DrawRectangle(rect, Color.Black, 1);
            // Remove rotation and draw the bounding rectangle where the non-rotated text would have been:
            g.Transform = Matrix3x2.Identity;
            g.DrawRectangle(rect, Color.ForestGreen, 1);
            //
            doc.Save(stream);
        }
コード例 #13
0
        static void Main(string[] args)
        {
            Console.WriteLine("DioDocs for PDF. PDF Form Data Import!");

            var doc = new GcPdfDocument();

            // PDFを読み込み
            doc.Load(new FileStream("grapecity_order_template.pdf", FileMode.Open, FileAccess.Read));

            // FDFファイルからデータを入力
            //FileStream stream = new FileStream("FormData_FDF.fdf", FileMode.Open, FileAccess.Read);
            //doc.ImportFormDataFromFDF(stream);

            // XFDFファイルからデータを入力
            FileStream stream = new FileStream("FormData_XFDF.xfdf", FileMode.Open, FileAccess.Read);

            doc.ImportFormDataFromXFDF(stream);

            // XMLファイルからデータを入力
            //FileStream stream = new FileStream("FormData_XML.xml", FileMode.Open, FileAccess.Read);
            //doc.ImportFormDataFromXML(stream);

            // PDFを保存
            doc.Save("grapecity_order_embed.pdf");
        }
コード例 #14
0
        public void CreatePDF(Stream stream)
        {
            GcPdfDocument doc = new GcPdfDocument();

            // The original file stream must be kept open while working with the loaded PDF,
            // see @{LoadPDF} for details:
            using (var fs = new FileStream(Path.Combine("Resources", "PDFs", "Transforms.pdf"), FileMode.Open, FileAccess.Read))
            {
                doc.Load(fs);
                // Find all 'Text drawn at', using case-sensitive search:
                var finds = doc.FindText(
                    new FindTextParams("Text drawn at", false, true),
                    OutputRange.All);

                // Highlight all finds: first, find all pages where the text was found
                var pgIndices = finds.Select(f_ => f_.PageIndex).Distinct();
                // Loop through pages, on each page insert a new content stream at index 0,
                // so that our highlights go UNDER the original content:
                foreach (int pgIdx in pgIndices)
                {
                    var page = doc.Pages[pgIdx];
                    PageContentStream pcs = page.ContentStreams.Insert(0);
                    var g = pcs.GetGraphics(page);
                    foreach (var find in finds.Where(f_ => f_.PageIndex == pgIdx))
                    {
                        // Note the solid color used to fill the polygon:
                        g.FillPolygon(find.Bounds, Color.CadetBlue);
                        g.DrawPolygon(find.Bounds, Color.Blue);
                    }
                }
                // Done:
                doc.Save(stream);
            }
        }
コード例 #15
0
ファイル: WordIndex.cs プロジェクト: GrapeCity/GcPdf
        // Creates a sample document with 100 pages of 'lorem ipsum':
        private string MakeDocumentToIndex()
        {
            const int N     = 100;
            string    tfile = Path.GetTempFileName();

            using (var fsOut = new FileStream(tfile, FileMode.Open, FileAccess.ReadWrite))
            {
                var tdoc = new GcPdfDocument();
                // See StartEndDoc for details on StartDoc/EndDoc mode:
                tdoc.StartDoc(fsOut);
                // Prep a TextLayout to hold/format the text:
                var tl = new TextLayout(72);
                tl.FontCollection         = _fc;
                tl.DefaultFormat.FontName = _fontFamily;
                tl.DefaultFormat.FontSize = 12;
                // Use TextLayout to layout the whole page including margins:
                tl.MaxHeight       = tdoc.PageSize.Height;
                tl.MaxWidth        = tdoc.PageSize.Width;
                tl.MarginAll       = 72;
                tl.FirstLineIndent = 72 / 2;
                // Generate the document:
                for (int pageIdx = 0; pageIdx < N; ++pageIdx)
                {
                    tl.Append(Common.Util.LoremIpsum(1));
                    tl.PerformLayout(true);
                    tdoc.NewPage().Graphics.DrawTextLayout(tl, PointF.Empty);
                    tl.Clear();
                }
                tdoc.EndDoc();
            }
            return(tfile);
        }
コード例 #16
0
        public int CreatePDF(Stream stream)
        {
            var doc = new GcPdfDocument();

            using (var fs = new FileStream(Path.Combine("Resources", "PDFs", "TimeSheet.pdf"), FileMode.Open, FileAccess.Read))
            {
                doc.Load(fs);

                // Fields can be children of other fields, so we use
                // a recursive method to iterate through the whole tree:
                removeSignatureFields(doc.AcroForm.Fields);

                // Done:
                doc.Save(stream);
                return(doc.Pages.Count);

                void removeSignatureFields(FieldCollection fields)
                {
                    for (int i = fields.Count - 1; i >= 0; --i)
                    {
                        removeSignatureFields(fields[i].Children);
                        // Note: if we just wanted to remove the signature
                        // without removing the field itself, we would do:
                        // ((SignatureField)fields[i]).Value = null;
                        if (fields[i] is SignatureField)
                        {
                            fields.RemoveAt(i);
                        }
                    }
                }
            }
        }
コード例 #17
0
ファイル: WordIndex.cs プロジェクト: GrapeCity/GcPdf
        // Main sample entry:
        public int CreatePDF(Stream stream)
        {
            // Set up a font collection with the fonts we need:
            _fc.RegisterDirectory(Path.Combine("Resources", "Fonts"));

            // Get the PDF to add index to:
            string tfile = Path.Combine("Resources", "PDFs", "CompleteJavaScriptBook.pdf");

            // The list of words on which we will build the index:
            var words = _keywords.Distinct(StringComparer.InvariantCultureIgnoreCase).Where(w_ => !string.IsNullOrEmpty(w_));

            // Load the PDF and add the index:
            using (var fs = new FileStream(tfile, FileMode.Open, FileAccess.Read))
            {
                var doc = new GcPdfDocument();
                doc.Load(fs);
                //
                int origPageCount = doc.Pages.Count;
                // Build and add the index:
                AddWordIndex(doc, words);
                // Open document on the first index page by default
                // (may not work in browser viewers, but works in Acrobat):
                doc.OpenAction = new DestinationFit(origPageCount);
                // Done:
                doc.Save(stream);
                return(doc.Pages.Count);
            }
        }
コード例 #18
0
        public void Create(string platformname, string key, string connectionstring)
        {
            // ライセンスキー設定
            //GcPdfDocument.SetLicenseKey(key);

            // PDFドキュメントを作成します。
            GcPdfDocument doc = new GcPdfDocument();

            // ページを追加し、そのグラフィックスを取得します。
            GcPdfGraphics g = doc.NewPage().Graphics;

            // ページに文字列を描画します。
            g.DrawString("Hello, DioDocs!" + Environment.NewLine + "from " + platformname,
                         new TextFormat()
            {
                Font = StandardFonts.Helvetica, FontSize = 12
            },
                         new PointF(72, 72));

            // メモリストリームに保存
            MemoryStream ms = new MemoryStream();

            doc.Save(ms, false);
            ms.Seek(0, SeekOrigin.Begin);

            // BLOBストレージにアップロード
            AzStorage storage = new AzStorage(connectionstring);

            storage.UploadPdfAsync(ms);
        }
コード例 #19
0
ファイル: FindText.cs プロジェクト: GrapeCity/GcPdf
        public void CreatePDF(Stream stream)
        {
            GcPdfDocument doc = new GcPdfDocument();

            // The original file stream must be kept open while working with the loaded PDF, see LoadPDF for details:
            using (var fs = new FileStream(Path.Combine("Resources", "PDFs", "BalancedColumns.pdf"), FileMode.Open, FileAccess.Read))
            {
                doc.Load(fs);
                // Find all 'lorem', using case-insensitive word search:
                var findsLorem = doc.FindText(
                    new FindTextParams("lorem", true, false),
                    OutputRange.All);
                // Ditto for 'ipsum':
                var findsIpsum = doc.FindText(
                    new FindTextParams("ipsum", true, false),
                    OutputRange.All);

                // Highlight all 'lorem' using semi-transparent orange red:
                foreach (var find in findsLorem)
                {
                    doc.Pages[find.PageIndex].Graphics.FillPolygon(find.Bounds, Color.FromArgb(100, Color.OrangeRed));
                }
                // Put a violet red border around all 'ipsum':
                foreach (var find in findsIpsum)
                {
                    doc.Pages[find.PageIndex].Graphics.DrawPolygon(find.Bounds, Color.MediumVioletRed);
                }

                // Done:
                doc.Save(stream);
            }
        }
コード例 #20
0
        public void CreatePDF(Stream stream)
        {
            Func <string> makePara = () => Common.Util.LoremIpsum(1, 5, 10, 15, 30);

            var doc = new GcPdfDocument();
            var g   = doc.NewPage().Graphics;
            // Using Graphics.CreateTextLayout() ensures that TextLayout's resolution
            // is set to the same value as that of the graphics (which is 72 dpi by default):
            var tl = g.CreateTextLayout();

            // Default font:
            tl.DefaultFormat.Font     = StandardFonts.Times;
            tl.DefaultFormat.FontSize = 12;
            // Set TextLayout to the whole page:
            tl.MaxWidth  = doc.PageSize.Width;
            tl.MaxHeight = doc.PageSize.Height;
            // ...and have it manage the page margins (1" all around):
            tl.MarginAll = tl.Resolution;
            // First line offset 1/2":
            tl.FirstLineIndent = 72 / 2;
            // 1.5 line spacing:
            tl.LineSpacingScaleFactor = 1.5f;
            //
            tl.Append(makePara());
            tl.PerformLayout(true);
            // Render text at (0,0) (margins are added by TextLayout):
            g.DrawTextLayout(tl, PointF.Empty);
            // Done:
            doc.Save(stream);
        }
コード例 #21
0
ファイル: Transforms.cs プロジェクト: GrapeCity/GcPdf
        public void CreatePDF(Stream stream)
        {
            const string baseTxt = "Text drawn at (0,36) in a 4\"x2\" box";
            var          doc     = new GcPdfDocument();
            var          page    = doc.NewPage();
            var          g       = page.Graphics;
            var          box     = new RectangleF(0, 36, 72 * 4, 72 * 2);

            // #1:
            DrawBox($"Box 1: {baseTxt}, no transformations.", g, box);
            //
            var translate0 = Matrix3x2.CreateTranslation(72 * 1, 72 * 4);
            var scale0     = Matrix3x2.CreateScale(0.5f);

            // Transforms are applied in order from last to first.

            // #2:
            g.Transform =
                scale0 *
                translate0;
            DrawBox($"Box 2: {baseTxt}, translated by (1\",4\") and scaled by 0.5.", g, box);
            // #3:
            g.Transform =
                translate0 *
                scale0;
            DrawBox($"Box 3: {baseTxt}, scaled by 0.5 and translated by (1\",4\").", g, box);
            //
            var translate1 = Matrix3x2.CreateTranslation(72 * 3, 72 * 5);
            var scale1     = Matrix3x2.CreateScale(0.7f);
            var rotate0    = Matrix3x2.CreateRotation((float)(-70 * Math.PI) / 180f); // 70 degrees CCW

            // #4:
            g.Transform =
                rotate0 *
                translate1 *
                scale1;
            DrawBox($"Box 4: {baseTxt}, scaled by 0.7, translated by (3\",5\"), and rotated 70 degrees counterclockwise.", g, box);
            // #5:
            g.Transform =
                Matrix3x2.CreateTranslation(36, 72) *
                g.Transform;
            DrawBox($"Box 5: {baseTxt}, applied current transform (Box 4), and translated by (1/2\",1\").", g, box);
            // #6:
            g.Transform =
                // rotate0 *
                Matrix3x2.CreateSkew((float)(-45 * Math.PI) / 180f, (float)(20 * Math.PI) / 180f) *
                Matrix3x2.CreateTranslation(72 * 3, 72 * 7);
            DrawBox($"Box 6: {baseTxt}, translated by (3\",7\"), and skewed -45 degrees on axis X and 20 degrees on axis Y.", g, box);
            // #7:
            g.Transform =
                Matrix3x2.CreateRotation((float)Math.PI) *
                Matrix3x2.CreateTranslation(page.Size.Width - 72, page.Size.Height - 72);
            DrawBox($"Box 7: {baseTxt}, translated by (7.5\",10\"), and rotated by 180 degrees.", g, box);
            // We can remove any transformations on a graphics like so:
            g.Transform = Matrix3x2.Identity;

            // Done:
            doc.Save(stream);
        }
コード例 #22
0
ファイル: SignDoc.cs プロジェクト: GrapeCity/GcPdf
        public int CreatePDF(Stream stream)
        {
            GcPdfDocument doc  = new GcPdfDocument();
            Page          page = doc.NewPage();
            TextFormat    tf   = new TextFormat()
            {
                Font = StandardFonts.Times, FontSize = 14
            };

            page.Graphics.DrawString(
                "Hello, World!\r\nSigned below by GcPdfWeb SignDoc sample.",
                tf, new PointF(72, 72));

            // Init a test certificate:
            var pfxPath           = Path.Combine("Resources", "Misc", "GcPdfTest.pfx");
            X509Certificate2 cert = new X509Certificate2(File.ReadAllBytes(pfxPath), "qq",
                                                         X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
            SignatureProperties sp = new SignatureProperties();

            sp.Certificate = cert;
            sp.Location    = "GcPdfWeb Sample Browser";
            sp.SignerName  = "GcPdfWeb";

            // Init a signature field to hold the signature:
            SignatureField sf = new SignatureField();

            sf.Widget.Rect                     = new RectangleF(72, 72 * 2, 72 * 4, 36);
            sf.Widget.Page                     = page;
            sf.Widget.BackColor                = Color.LightSeaGreen;
            sf.Widget.TextFormat.Font          = StandardFonts.Helvetica;
            sf.Widget.ButtonAppearance.Caption = $"Signer: {sp.SignerName}\r\nLocation: {sp.Location}";
            // Add the signature field to the document:
            doc.AcroForm.Fields.Add(sf);
            // Connect the signature field and signature props:
            sp.SignatureField = sf;

            // Sign and save the document:
            // NOTES:
            // - Signing and saving is an atomic operation, the two cannot be separated.
            // - The stream passed to the Sign() method must be readable.
            doc.Sign(sp, stream);

            // Rewind the stream to read the document just created
            // into another GcPdfDocument and verify the signature:
            stream.Seek(0, SeekOrigin.Begin);
            GcPdfDocument doc2 = new GcPdfDocument();

            doc2.Load(stream);
            SignatureField sf2 = (SignatureField)doc2.AcroForm.Fields[0];

            if (!sf2.Value.VerifySignature())
            {
                throw new Exception("Failed to verify the signature");
            }

            // Done (the generated and signed document has already been saved to 'stream').
            return(doc.Pages.Count);
        }
コード例 #23
0
        public int CreatePDF(Stream stream)
        {
            const int NPAR = 40;
            var       doc  = new GcPdfDocument();
            var       tl   = new TextLayout(72)
            {
                FirstLineIndent = 72 / 2,
                MaxWidth        = doc.PageSize.Width,
                MaxHeight       = doc.PageSize.Height,
                MarginAll       = 72,
            };

            tl.DefaultFormat.Font     = StandardFonts.Times;
            tl.DefaultFormat.FontSize = 12;
            // Text format for paragraphs kept together with next one:
            var tf = new TextFormat(tl.DefaultFormat)
            {
                FontSize = tl.DefaultFormat.FontSize + 2,
                FontBold = true
            };

            // We add a number of random 'lorem ipsum' paragraphs to this document,
            // adding a 'caption' before each paragraph which is kept together
            // with the following 'lorem ipsum' paragraph:
            for (int i = 0; i < NPAR; i++)
            {
                // 'Caption' kept together with the next paragraph:
                tl.Append("Caption kept together with the next paragraph. No page break after this.", tf);
                // AppendParagraphBreak adds a paragraph break but prevents a page break between the two paragraphs:
                tl.AppendParagraphBreak();
                // Random paragraph after 'caption':
                tl.Append(Common.Util.LoremIpsum(1));
            }
            tl.PerformLayout(true);
            // We force all paragraph lines to stay on the same page,
            // this makes it more obvious that 'caption' and following paragraph
            // are kept on the same page:
            TextSplitOptions to = new TextSplitOptions(tl)
            {
                KeepParagraphLinesTogether = true,
            };

            // In a loop, split and render the text:
            while (true)
            {
                // 'rest' will accept the text that did not fit:
                var splitResult = tl.Split(to, out TextLayout rest);
                doc.Pages.Add().Graphics.DrawTextLayout(tl, PointF.Empty);
                if (splitResult != SplitResult.Split)
                {
                    break;
                }
                tl = rest;
            }
            // Done:
            doc.Save(stream);
            return(doc.Pages.Count);
        }
コード例 #24
0
ファイル: SoundAnnotations.cs プロジェクト: GrapeCity/GcPdf
        public void CreatePDF(Stream stream)
        {
            var doc  = new GcPdfDocument();
            var page = doc.NewPage();
            var g    = page.Graphics;
            // User names for annotations' authors:
            var user1 = "Aiff Ding";
            var user2 = "Wav Dong";

            TextFormat tf = new TextFormat()
            {
                Font = StandardFonts.Helvetica, FontSize = 10
            };
            var noteWidth = 72 * 3;
            var gap       = 8;

            var rc = Common.Util.AddNote(
                "This sample demonstrates adding sound annotations using GcPdf. " +
                "The track associated with an annotation can be played in a viewer that supports it. " +
                "PDF supports AIFF and WAV tracks in sound annotations.",
                page);

            // AIFF sound annotation:
            var ip = new PointF(rc.X, rc.Bottom + gap);

            rc = Common.Util.AddNote("A red sound annotation is placed to the right of this note. Double click the icon to play the sound.",
                                     page, new RectangleF(ip.X, ip.Y, noteWidth, 100));
            var aiffAnnot = new SoundAnnotation()
            {
                UserName = user1,
                Contents = "Sound annotation with an AIFF track.",
                Rect     = new RectangleF(rc.Right, rc.Top, 24, 24),
                Icon     = SoundAnnotationIcon.Speaker,
                Color    = Color.Red,
                Sound    = SoundObject.FromFile(Path.Combine("Resources", "Sounds", "ding.aiff"), AudioFormat.Aiff)
            };

            page.Annotations.Add(aiffAnnot);

            // WAV sound annotation:
            ip = new PointF(rc.X, rc.Bottom + gap);
            rc = Common.Util.AddNote("A blue sound annotation is placed to the right of this note. Double click the icon to play the sound.",
                                     page, new RectangleF(ip.X, ip.Y, noteWidth, 100));
            var wavAnnot = new SoundAnnotation()
            {
                UserName = user2,
                Contents = "Sound annotation with a WAV track.",
                Rect     = new RectangleF(rc.Right, rc.Top, 24, 24),
                Icon     = SoundAnnotationIcon.Mic,
                Color    = Color.Blue,
                Sound    = SoundObject.FromFile(Path.Combine("Resources", "Sounds", "dong.wav"), AudioFormat.Wav)
            };

            page.Annotations.Add(wavAnnot);

            // Done:
            doc.Save(stream);
        }
コード例 #25
0
ファイル: TimeSheet.cs プロジェクト: GrapeCity/GcPdf
        // Sets the value of a field with the specified name:
        private void SetFieldValue(GcPdfDocument doc, string name, string value)
        {
            var fld = doc.AcroForm.Fields.First(f_ => f_.Name == name);

            if (fld != null)
            {
                fld.Value = value;
            }
        }
コード例 #26
0
        // Main entry point:
        public void CreatePDF(Stream stream)
        {
            var doc  = new GcPdfDocument();
            var page = doc.NewPage();

            RenderNodes(ref page, new PointF(Layout.Margin, Layout.Margin), _arthrapods.Children, 0);
            // Done:
            doc.Save(stream);
        }
コード例 #27
0
ファイル: Ligatures.cs プロジェクト: GrapeCity/GcPdf
        public void CreatePDF(Stream stream)
        {
            // The list of common Latin ligatures:
            const string latinLigatures = "fi, fj, fl, ff, ffi, ffl.";

            // Set up ligature-related font features:
            // All ON:
            FontFeature[] allOn = new FontFeature[]
            {
                new FontFeature(FeatureTag.clig, true), // Contextual Ligatures
                new FontFeature(FeatureTag.dlig, true), // Discretionary Ligatures
                new FontFeature(FeatureTag.hlig, true), // Historical Ligatures
                new FontFeature(FeatureTag.liga, true), // Standard Ligatures
                new FontFeature(FeatureTag.rlig, true), // Required Ligatures
            };
            // All OFF:
            FontFeature[] allOff = new FontFeature[]
            {
                new FontFeature(FeatureTag.clig, false),
                new FontFeature(FeatureTag.dlig, false),
                new FontFeature(FeatureTag.hlig, false),
                new FontFeature(FeatureTag.liga, false),
                new FontFeature(FeatureTag.rlig, false),
            };
            var doc = new GcPdfDocument();
            var g   = doc.NewPage().Graphics;
            // Text insertion point:
            PointF     ip = new PointF(72, 72);
            TextFormat tf = new TextFormat();

            tf.Font     = Font.FromFile(Path.Combine("Resources", "Fonts", "times.ttf"));
            tf.FontSize = 20;
            g.DrawString($"Common Latin ligatures, font {tf.Font.FontFamilyName}", tf, ip);
            ip.Y += 36;
            // Turn all ligature features OFF:
            tf.FontFeatures = allOff;
            g.DrawString($"All ligature features OFF: {latinLigatures}", tf, ip);
            ip.Y += 36;
            // Turn all ligature features ON:
            tf.FontFeatures = allOn;
            g.DrawString($"All ligature features ON: {latinLigatures}", tf, ip);
            ip.Y += 72;
            // Repeat with a different font:
            tf.Font = Font.FromFile(Path.Combine("Resources", "Fonts", "Gabriola.ttf"));
            g.DrawString($"Common Latin ligatures, font {tf.Font.FontFamilyName}", tf, ip);
            ip.Y += 36;
            // Turn all ligature features OFF:
            tf.FontFeatures = allOff;
            g.DrawString($"All ligature features OFF: {latinLigatures}", tf, ip);
            ip.Y += 36;
            // Turn all ligature features ON:
            tf.FontFeatures = allOn;
            g.DrawString($"All ligature features ON: {latinLigatures}", tf, ip);
            // Done:
            doc.Save(stream);
        }
コード例 #28
0
ファイル: TimeSheet.cs プロジェクト: GrapeCity/GcPdf
        // Fill in employee info and working hours with sample data:
        private void FillEmployeeData(GcPdfDocument doc)
        {
            // For the purposes of this sample, we fill the form with random data:
            SetFieldValue(doc, _Names.EmpName, "Jaime Smith");
            SetFieldValue(doc, _Names.EmpNum, "12345");
            SetFieldValue(doc, _Names.EmpDep, "Research & Development");
            SetFieldValue(doc, _Names.EmpTitle, "Senior Developer");
            SetFieldValue(doc, _Names.EmpStatus, "Full Time");
            var      rand    = new Random((int)DateTime.Now.Ticks);
            DateTime workday = DateTime.Now.AddDays(-15);

            while (workday.DayOfWeek != DayOfWeek.Sunday)
            {
                workday = workday.AddDays(1);
            }
            TimeSpan wkTot = TimeSpan.Zero, wkReg = TimeSpan.Zero, wkOvr = TimeSpan.Zero;

            for (int i = 0; i < 7; ++i)
            {
                // Start time:
                var start = new DateTime(workday.Year, workday.Month, workday.Day, rand.Next(6, 12), rand.Next(0, 59), 0);
                SetFieldValue(doc, _Names.DtNames[_Names.Dows[i]][0], start.ToShortDateString());
                SetFieldValue(doc, _Names.DtNames[_Names.Dows[i]][1], start.ToShortTimeString());
                // End time:
                var end = start.AddHours(rand.Next(8, 14)).AddMinutes(rand.Next(0, 59));
                SetFieldValue(doc, _Names.DtNames[_Names.Dows[i]][2], end.ToShortTimeString());
                var tot = end - start;
                var reg = TimeSpan.FromHours((start.DayOfWeek != DayOfWeek.Saturday && start.DayOfWeek != DayOfWeek.Sunday) ? 8 : 0);
                var ovr = tot.Subtract(reg);
                SetFieldValue(doc, _Names.DtNames[_Names.Dows[i]][3], reg.ToString(@"hh\:mm"));
                SetFieldValue(doc, _Names.DtNames[_Names.Dows[i]][4], ovr.ToString(@"hh\:mm"));
                SetFieldValue(doc, _Names.DtNames[_Names.Dows[i]][5], tot.ToString(@"hh\:mm"));
                wkTot += tot;
                wkOvr += ovr;
                wkReg += reg;
                //
                workday = workday.AddDays(1);
            }
            SetFieldValue(doc, _Names.TotalReg, wkReg.TotalHours.ToString("F"));
            SetFieldValue(doc, _Names.TotalOvr, wkOvr.TotalHours.ToString("F"));
            SetFieldValue(doc, _Names.TotalHours, wkTot.TotalHours.ToString("F"));
            SetFieldValue(doc, _Names.EmpSignDate, workday.ToShortDateString());

            // 'Sign' the time sheet on behalf of the employee by drawing an image representing the signature
            // (see TimeSheetIncremental for digitally signing by both employee and supervisor):
            var empSignImage = Image.FromFile(Path.Combine("Resources", "ImagesBis", "signature.png"));

            _disposables.Add(empSignImage);
            var ia = new ImageAlign(ImageAlignHorz.Center, ImageAlignVert.Center, true, true, true, false, false)
            {
                KeepAspectRatio = true
            };

            doc.Pages[0].Graphics.DrawImage(empSignImage, _empSignRect, null, ia);
        }
コード例 #29
0
ファイル: UnicodeRanges.cs プロジェクト: GrapeCity/GcPdf
        public int CreatePDF(Stream stream)
        {
            // Setup:
            GcPdfDocument doc = new GcPdfDocument();
            TextLayout    tl  = new TextLayout(72)
            {
                MaxWidth  = doc.PageSize.Width,
                MaxHeight = doc.PageSize.Height,
                MarginAll = 72,
            };

            tl.DefaultFormat.FontSize = 7;
            var tfH = new TextFormat()
            {
                Font = StandardFonts.TimesBold, FontSize = 12
            };
            var tfP = new TextFormat()
            {
                Font = StandardFonts.Times, FontSize = 11
            };

            // Loop through all system fonts,
            // list Unicode ranges provided by each font:
            foreach (Font font in FontCollection.SystemFonts)
            {
                tl.AppendLine($"{font.FontFileName} [{font.FullFontName}] [{font.FontFamilyName}]", tfH);
                var shot = font.CreateFontTables(TableTag.OS2);
                tl.AppendLine(shot.GetUnicodeRanges(), tfP);
                tl.AppendLine();
            }

            // Split and render TextLayout as shown in the PaginatedText sample:
            TextSplitOptions to = new TextSplitOptions(tl)
            {
                MinLinesInFirstParagraph = 2,
                MinLinesInLastParagraph  = 2
            };

            tl.PerformLayout(true);
            while (true)
            {
                var splitResult = tl.Split(to, out TextLayout rest);
                doc.Pages.Add().Graphics.DrawTextLayout(tl, PointF.Empty);
                if (splitResult != SplitResult.Split)
                {
                    break;
                }
                tl = rest;
            }

            // Done:
            doc.Save(stream);
            return(doc.Pages.Count);
        }
コード例 #30
0
ファイル: StartEndDoc.cs プロジェクト: GrapeCity/GcPdf
        public int CreatePDF(Stream stream)
        {
            // Number of pages to generate:
            const int N   = Common.Util.LargeDocumentIterations;
            var       doc = new GcPdfDocument();

            // Start creating the document by this call:
            doc.StartDoc(stream);
            // Prep a TextLayout to hold/format the text:
            var tl = new TextLayout(72)
            {
                MaxWidth  = doc.PageSize.Width,
                MaxHeight = doc.PageSize.Height,
                MarginAll = 72,
            };

            tl.DefaultFormat.Font     = StandardFonts.Times;
            tl.DefaultFormat.FontSize = 12;
            // Start with a title page:
            tl.FirstLineIndent = 0;
            var fnt = Font.FromFile(Path.Combine("Resources", "Fonts", "yumin.ttf"));
            var tf0 = new TextFormat()
            {
                FontSize = 24, FontBold = true, Font = fnt
            };

            tl.Append(string.Format("Large Document\n{0} Pages of Lorem Ipsum\n\n", N), tf0);
            var tf1 = new TextFormat(tf0)
            {
                FontSize = 14, FontItalic = true
            };

            tl.Append(string.Format("Generated on {0}.", DateTime.Now), tf1);
            tl.TextAlignment = TextAlignment.Center;
            tl.PerformLayout(true);
            doc.Pages.Add().Graphics.DrawTextLayout(tl, PointF.Empty);
            tl.Clear();
            tl.FirstLineIndent = 36;
            tl.TextAlignment   = TextAlignment.Leading;
            // Generate the document:
            for (int pageIdx = 0; pageIdx < N; ++pageIdx)
            {
                tl.Append(Common.Util.LoremIpsum(1));
                tl.PerformLayout(true);
                doc.NewPage().Graphics.DrawTextLayout(tl, PointF.Empty);
                tl.Clear();
            }
            // NOTE: Certain operations (e.g. the one below) will throw an error when using StartDoc/EndDoc:
            //   doc.Pages.Insert(0);
            //
            // Done - call EndDoc instead of Save():
            doc.EndDoc();
            return(doc.Pages.Count);
        }