public void GetPageDetails_IfPdfDocHasThreePages_ThreePagesAddedIntoObjectEdition() { // Arrange var pdfDoc = new PDFDoc(); try { var pdfPage01 = pdfDoc.PageCreate(); var pdfPage02 = pdfDoc.PageCreate(); var pdfPage03 = pdfDoc.PageCreate(); pdfDoc.PagePushBack(pdfPage01); pdfDoc.PagePushBack(pdfPage02); pdfDoc.PagePushBack(pdfPage03); // Act _testEntityPrivate.Invoke(GetPageDetailsMethodName, pdfDoc); } finally { pdfDoc.Dispose(); } // Assert _objectEdition.PageCollection.Count.ShouldBe(3); }
public void GetPageDetails_IfPdfDocHasPage_SetsObjectEditionPageProperties() { // Arrange const int page01Index = 0; const int pdfPage01Number = 1; var pdfDoc = new PDFDoc(); int pdfPage01Width, pdfPage01Height; try { var pdfPage01 = pdfDoc.PageCreate(); pdfPage01Width = (int)pdfPage01.GetPageWidth(); pdfPage01Height = (int)pdfPage01.GetPageHeight(); pdfDoc.PagePushBack(pdfPage01); AddTextDataToPdfPage(pdfDoc, pdfPage01, PdfPageText); // Act _testEntityPrivate.Invoke(GetPageDetailsMethodName, pdfDoc); } finally { pdfDoc.Dispose(); } // Assert var page01 = _objectEdition.PageCollection[page01Index]; page01.PageNo.ShouldBe(pdfPage01Number); page01.DisplayNo.ShouldBe(pdfPage01Number.ToString()); page01.TextContent.ShouldBe(PdfPageText); page01.Width.ShouldBe(pdfPage01Width); page01.Height.ShouldBe(pdfPage01Height); }
public void GenerateImages_IfThumbnailDirectoriesDoesNotExist_CreatesDirectoriesByCountOfPages() { // Arrange const int pdfDocPageCount = 2; var thumbnailPath = string.Format("{0}{1}/", DummyImagePath, _thumbnailResolution); var createDirectoryCallCount = 0; ShimDirectory.ExistsString = (directoryPath) => { return(false); }; ShimDirectory.CreateDirectoryString = (directoryPath) => { if (directoryPath == thumbnailPath) { createDirectoryCallCount++; } return(null); }; ShimPDFDraw.AllInstances.ExportPageStringStringObj = (_, __, ___, ____, _____) => { }; using (var pdfDoc = new PDFDoc()) { for (var i = 0; i < pdfDocPageCount; i++) { pdfDoc.PagePushBack(pdfDoc.PageCreate()); } // Act _testEntityPrivate.Invoke(GenerateImagesMethodName, pdfDoc); } // Assert createDirectoryCallCount.ShouldBe(pdfDocPageCount); }
static void AddCovePage(PDFDoc doc) { // Here we dynamically generate cover page (please see ElementBuilder // sample for more extensive coverage of PDF creation API). Page page = doc.PageCreate(new Rect(0, 0, 200, 200)); using (ElementBuilder b = new ElementBuilder()) using (ElementWriter w = new ElementWriter()) { w.Begin(page); Font font = Font.Create(doc, "Arial", ""); w.WriteElement(b.CreateTextBegin(font, 12)); Element e = b.CreateTextRun("My PDF Collection"); e.SetTextMatrix(1, 0, 0, 1, 50, 96); e.GetGState().SetFillColorSpace(ColorSpace.CreateDeviceRGB()); e.GetGState().SetFillColor(new ColorPt(1, 0, 0)); w.WriteElement(e); w.WriteElement(b.CreateTextEnd()); w.End(); doc.PagePushBack(page); } // Alternatively we could import a PDF page from a template PDF document // (for an example please see PDFPage sample project). // ... }
public void GenerateImages_WhenCalled_GeneratesPageThumbnails() { // Arrange const int pdfDocPageCount = 2; var thumbnailPath = string.Format("{0}{1}/", DummyImagePath, _thumbnailResolution); ShimDirectory.ExistsString = (directoryPath) => { return(true); }; ShimDirectory.CreateDirectoryString = (directoryPath) => { return(null); }; var exportCallCount = 0; ShimPDFDraw.AllInstances.ExportPageStringStringObj = (pdfDraw, pdfPage, fileName, fileFormat, encoderHints) => { if (fileName.StartsWith(thumbnailPath, StringComparison.OrdinalIgnoreCase) && fileFormat.Equals("png", StringComparison.OrdinalIgnoreCase)) { exportCallCount++; } }; using (var pdfDoc = new PDFDoc()) { for (var i = 0; i < pdfDocPageCount; i++) { pdfDoc.PagePushBack(pdfDoc.PageCreate()); } // Act _testEntityPrivate.Invoke(GenerateImagesMethodName, pdfDoc); } // Assert exportCallCount.ShouldBe(pdfDocPageCount); }
private void btnNovoPdf_Click(object sender, System.EventArgs e) { // Using PDFNet related classes and methods, must // catch or throw PDFNetException try { using (PDFDoc doc = new PDFDoc()) { using (Stamper s = new Stamper(Stamper.SizeType.e_relative_scale, 0.5, 0.5)) { var randomNumber = new Random().Next(0, System.Convert.ToInt32(tbxNumMaxArquivos.Text)); doc.InitSecurityHandler(); // An example of creating a new page and adding it to // doc's sequence of pages Page newPg = doc.PageCreate(); doc.PagePushBack(newPg); s.SetAlignment(Stamper.HorizontalAlignment.e_horizontal_center, Stamper.VerticalAlignment.e_vertical_center); s.SetFontColor(new ColorPt(1, 0, 0)); // set text color to red s.StampText(doc, $"{tbxDefaultNewName.Text} document {randomNumber}", new PageSet(1, doc.GetPageCount())); var caminhoDestino = chkGerarWatchFolder.Checked ? CONVERTER_DEFAULT_OUTPUT_PATH : fbdCaminhoPasta.SelectedPath; // Save as a linearized file which is most popular // and effective format for quick PDF Viewing. doc.Save(caminhoDestino + $"\\{tbxDefaultNewName.Text}_{randomNumber}.pdf", SDFDoc.SaveOptions.e_linearized); } } } catch (PDFNetException ex) { MessageBox.Show(ex.Message); } }
static void Main(string[] args) { // Initialize PDFNet before using any PDFTron related // classes and methods (some exceptions can be found in API) PDFNet.Initialize(); // Using PDFNet related classes and methods, must catch or throw PDFNetException try { using (PDFDoc doc = new PDFDoc()) { doc.InitSecurityHandler(); // An example of creating a new page and adding it to // doc's sequence of pages Page newPg = doc.PageCreate(); doc.PagePushBack(newPg); // Save as a linearized file which is most popular // and effective format for quick PDF Viewing. doc.Save("linearized_output.pdf", SDFDoc.SaveOptions.e_linearized); System.Console.WriteLine("Done. Results saved in linearized_output.pdf"); } } catch (PDFNetException e) { System.Console.WriteLine(e); } }
private void Button_Click(object sender, RoutedEventArgs e) { try { using (PDFDoc doc = new PDFDoc()) { doc.InitSecurityHandler(); pdftron.PDF.Page newPg = doc.PageCreate(); doc.PagePushBack(newPg); Ink ink = Ink.Create(doc, new pdftron.PDF.Rect(110, 10, 300, 200)); pdftron.PDF.Point pt3 = new pdftron.PDF.Point(110, 10); //pt3.x = 110; pt3.y = 10; ink.SetPoint(0, 0, pt3); pt3.x = 150; pt3.y = 50; ink.SetPoint(0, 1, pt3); pt3.x = 190; pt3.y = 60; ink.SetPoint(0, 2, pt3); pt3.x = 180; pt3.y = 90; ink.SetPoint(1, 0, pt3); pt3.x = 190; pt3.y = 95; ink.SetPoint(1, 1, pt3); pt3.x = 200; pt3.y = 100; ink.SetPoint(1, 2, pt3); pt3.x = 166; pt3.y = 86; ink.SetPoint(2, 0, pt3); pt3.x = 196; pt3.y = 96; ink.SetPoint(2, 1, pt3); pt3.x = 221; pt3.y = 121; ink.SetPoint(2, 2, pt3); pt3.x = 288; pt3.y = 188; ink.SetPoint(2, 3, pt3); ink.SetColor(new ColorPt(0, 1, 1), 3); newPg.AnnotPushBack(ink); // Save as a linearized file which is most popular // and effective format for quick PDF Viewing. doc.Save("linearized_output.pdf", SDFDoc.SaveOptions.e_linearized); System.Console.WriteLine("Done. Results saved in linearized_output.pdf"); MessageBox.Show("Done. Results saved in linearized_output.pdf", "Document Creation"); } } catch (PDFNetException ex) { System.Console.WriteLine(ex.Message); } }
public void GetPageDetails_IfPdfPageHasUriLinkWithoutScheme_ObjectEditionHasPageUriLinkAddedUriScheme() { // Arrange const int page02Index = 1; var pdfDoc = new PDFDoc(); try { var pdfPage01 = pdfDoc.PageCreate(); var pdfPage02 = pdfDoc.PageCreate(); pdfDoc.PagePushBack(pdfPage01); pdfDoc.PagePushBack(pdfPage02); // create annot of pdfPage02 // uri type of annot to an uri with mailto scheme var uriAcion = PDFAction.CreateURI(pdfDoc, WebUriWithoutScheme); var linkAnnot = Annot.CreateLink(pdfDoc, new Rect(X1, Y1, X2, Y2), uriAcion); pdfPage02.AnnotInsert(0, linkAnnot); // Act _testEntityPrivate.Invoke(GetPageDetailsMethodName, pdfDoc); } finally { pdfDoc.Dispose(); } // Assert var page02LinkCollection = _objectEdition.PageCollection[page02Index].LinkCollection; var page02Links = ConvertToLinkArray(page02LinkCollection); page02Links.ShouldSatisfyAllConditions( () => page02Links.Length.ShouldBe(1), () => page02Links.ShouldContain(link => link.LinkType == UriLinkType), () => page02Links.First().LinkURL.ShouldStartWith(HttpScheme)); }
public void GetPageDetails_IfPdfPageHasGoToLink_ObjectEditionPageHasGoToLink() { // Arrange const int page01Index = 0; var pdfDoc = new PDFDoc(); try { var pdfPage01 = pdfDoc.PageCreate(); var pdfPage02 = pdfDoc.PageCreate(); pdfDoc.PagePushBack(pdfPage01); pdfDoc.PagePushBack(pdfPage02); // create annot of pdfPage01 // goto type of annot links to pdfPage02 var destination = Destination.CreateFit(pdfPage02); var gotoAction = PDFAction.CreateGoto(destination); var linkAnnot = Annot.CreateLink(pdfDoc, new Rect(X1, Y1, X2, Y2), gotoAction); pdfPage01.AnnotInsert(0, linkAnnot); // Act _testEntityPrivate.Invoke(GetPageDetailsMethodName, pdfDoc); } finally { pdfDoc.Dispose(); } // Assert var page01LinkCollection = _objectEdition.PageCollection[page01Index].LinkCollection; var page01Links = ConvertToLinkArray(page01LinkCollection); page01Links.ShouldSatisfyAllConditions( () => page01Links.Length.ShouldBe(1), () => page01Links.ShouldContain(link => link.LinkType == GoToLinkType)); }
static void SignPDF() { PDFNet.Initialize(); // Create a page using (var doc = new PDFDoc()) { var page = doc.PageCreate(new Rect(0, 0, 595, 842)); page.SetRotation(Page.Rotate.e_0); page.SetCropBox(new Rect(0, 0, 595, 842)); doc.PagePushBack(page); var rect = new Rect(0, 0, 0, 0); var fieldId = Guid.NewGuid().ToString(); var fieldToSign = doc.FieldCreate(fieldId, Field.Type.e_signature); var signatureAnnotation = Widget.Create(doc, rect, fieldToSign); signatureAnnotation.SetFlag(Annot.Flag.e_print, true); signatureAnnotation.SetPage(page); var widgetObj = signatureAnnotation.GetSDFObj(); widgetObj.PutNumber("F", 132.0); widgetObj.PutName("Type", "Annot"); page.AnnotPushBack(signatureAnnotation); //Create the signature handler var sigHandler = new RemoteSignatureTimeStampPdfHandler(new HttpClient()); //Add handler to PDFDoc instance var sigHandlerId = doc.AddSignatureHandler(sigHandler); // Add the SignatureHandler instance to PDFDoc, making sure to keep track of it using the ID returned. var sigDict = fieldToSign.UseSignatureHandler(sigHandlerId); var signatureObject = signatureAnnotation.GetSDFObj(); var cultureInfo = new CultureInfo("en-US"); var gmt1Date = DateTime.Now; var value = gmt1Date.ToString("'D:'yyyyMMddHHmmsszzz", cultureInfo); // Add signing date sigDict.PutString("M", value); doc.Save(SDFDoc.SaveOptions.e_incremental); } }
static void Main(string[] args) { PDFNet.Initialize(); try { using (PDFDoc doc = new PDFDoc()) { Page page = doc.PageCreate(); doc.PagePushBack(page); Obj annots = doc.CreateIndirectArray(); page.GetSDFObj().Put("Annots", annots); Create3DAnnotation(doc, annots); doc.Save(output_path + "dice_u3d.pdf", SDFDoc.SaveOptions.e_linearized); } Console.WriteLine("Done"); } catch (PDFNetException e) { Console.WriteLine(e.Message); } }
public void GenerateImages_IfAnErrorOccured_ThrowsException() { // Arrange ShimDirectory.ExistsString = (directoryPath) => { return(true); }; ShimDirectory.CreateDirectoryString = (directoryPath) => { return(null); }; ShimPDFDraw.AllInstances.ExportPageStringStringObj = (_, __, ___, ____, _____) => { throw new Exception(); }; var generateImagesAction = default(ActionDelegate); using (var pdfDoc = new PDFDoc()) { pdfDoc.PagePushBack(pdfDoc.PageCreate()); // Act generateImagesAction = new ActionDelegate(() => { _testEntityPrivate.Invoke(GenerateImagesMethodName, pdfDoc); }); } // Assert generateImagesAction.ShouldThrow <Exception>(); }
public void GetPageDetails_IfPdfPageHasNoAnnots_ObjectEditionPageHasNoLinks() { // Arrange const int page01Index = 0; var pdfDoc = new PDFDoc(); try { var pdfPage01 = pdfDoc.PageCreate(); pdfDoc.PagePushBack(pdfPage01); // Act _testEntityPrivate.Invoke(GetPageDetailsMethodName, pdfDoc); } finally { pdfDoc.Dispose(); } // Assert var page01LinkCollection = _objectEdition.PageCollection[page01Index].LinkCollection; page01LinkCollection.Count.ShouldBe(0); }
// Note: This demo assumes that 'arialuni.ttf' is present in '/Samples/TestFiles' // directory. Arial Unicode MS is about 24MB in size and it comes together with Windows and // MS Office. // // For more information about Arial Unicode MS, please consult the following Microsoft Knowledge // Base Article: WD2002: General Information About the Arial Unicode MS Font // http://support.microsoft.com/support/kb/articles/q287/2/47.asp // // For more information consult: // http://office.microsoft.com/search/results.aspx?Scope=DC&Query=font&CTT=6&Origin=EC010331121033 // http://www.microsoft.com/downloads/details.aspx?FamilyID=1F0303AE-F055-41DA-A086-A65F22CB5593 // // In case you don't have access to Arial Unicode MS you can use cyberbit.ttf // (ftp://ftp.netscape.com/pub/communicator/extras/fonts/windows/) instead. // static void Main(string[] args) { PDFNet.Initialize(); // Relative path to the folder containing test files. // string input_path = "../../TestFiles/"; string output_path = "../../TestFiles/Output/"; try { using (PDFDoc doc = new PDFDoc()) { using (ElementBuilder eb = new ElementBuilder()) { using (ElementWriter writer = new ElementWriter()) { // Start a new page ------------------------------------ Page page = doc.PageCreate(new Rect(0, 0, 612, 794)); writer.Begin(page); // begin writing to this page Font fnt; try { // Full font embedding fnt = Font.Create(doc, "Arial", ""); // To embed the font file directly use: // fnt = Font.CreateCIDTrueTypeFont(doc, input_path + "arialuni.ttf", true, true); // Example of font substitution // fnt = Font.CreateCIDTrueTypeFont(doc, input_path + "arialuni.ttf", false); } catch (PDFNetException e) { Console.WriteLine(e.Message); Console.WriteLine(); Console.WriteLine("'arialuni.ttf' font file was not found in 'Samples/TestFiles' directory."); return; } Element element = eb.CreateTextBegin(fnt, 1); element.SetTextMatrix(10, 0, 0, 10, 50, 600); element.GetGState().SetLeading(2); // Set the spacing between lines writer.WriteElement(element); // Hello World!!! string hello = "Hello World!"; writer.WriteElement(eb.CreateUnicodeTextRun(hello)); writer.WriteElement(eb.CreateTextNewLine()); // Latin char[] latin = { 'a', 'A', 'b', 'B', 'c', 'C', 'd', 'D', '\x45', '\x0046', '\x00C0', '\x00C1', '\x00C2', '\x0143', '\x0144', '\x0145', '\x0152', '1', '2' // etc. }; writer.WriteElement(eb.CreateUnicodeTextRun(new string(latin))); writer.WriteElement(eb.CreateTextNewLine()); // Greek char[] greek = { (char)0x039E, (char)0x039F, (char)0x03A0, (char)0x03A1, (char)0x03A3, (char)0x03A6, (char)0x03A8, (char)0x03A9 // etc. }; writer.WriteElement(eb.CreateUnicodeTextRun(new string(greek))); writer.WriteElement(eb.CreateTextNewLine()); // Cyrillic char[] cyrillic = { (char)0x0409, (char)0x040A, (char)0x040B, (char)0x040C, (char)0x040E, (char)0x040F, (char)0x0410, (char)0x0411, (char)0x0412, (char)0x0413, (char)0x0414, (char)0x0415, (char)0x0416, (char)0x0417, (char)0x0418, (char)0x0419 // etc. }; writer.WriteElement(eb.CreateUnicodeTextRun(new string(cyrillic))); writer.WriteElement(eb.CreateTextNewLine()); // Hebrew char[] hebrew = { (char)0x05D0, (char)0x05D1, (char)0x05D3, (char)0x05D3, (char)0x05D4, (char)0x05D5, (char)0x05D6, (char)0x05D7, (char)0x05D8, (char)0x05D9, (char)0x05DA, (char)0x05DB, (char)0x05DC, (char)0x05DD, (char)0x05DE, (char)0x05DF, (char)0x05E0, (char)0x05E1 // etc. }; writer.WriteElement(eb.CreateUnicodeTextRun(new string(hebrew))); writer.WriteElement(eb.CreateTextNewLine()); // Arabic char[] arabic = { (char)0x0624, (char)0x0625, (char)0x0626, (char)0x0627, (char)0x0628, (char)0x0629, (char)0x062A, (char)0x062B, (char)0x062C, (char)0x062D, (char)0x062E, (char)0x062F, (char)0x0630, (char)0x0631, (char)0x0632, (char)0x0633, (char)0x0634, (char)0x0635 // etc. }; writer.WriteElement(eb.CreateUnicodeTextRun(new string(arabic))); writer.WriteElement(eb.CreateTextNewLine()); // Thai char[] thai = { (char)0x0E01, (char)0x0E02, (char)0x0E03, (char)0x0E04, (char)0x0E05, (char)0x0E06, (char)0x0E07, (char)0x0E08, (char)0x0E09, (char)0x0E0A, (char)0x0E0B, (char)0x0E0C, (char)0x0E0D, (char)0x0E0E, (char)0x0E0F, (char)0x0E10, (char)0x0E11, (char)0x0E12 // etc. }; writer.WriteElement(eb.CreateUnicodeTextRun(new string(thai))); writer.WriteElement(eb.CreateTextNewLine()); // Hiragana - Japanese char[] hiragana = { (char)0x3041, (char)0x3042, (char)0x3043, (char)0x3044, (char)0x3045, (char)0x3046, (char)0x3047, (char)0x3048, (char)0x3049, (char)0x304A, (char)0x304B, (char)0x304C, (char)0x304D, (char)0x304E, (char)0x304F, (char)0x3051, (char)0x3051, (char)0x3052 // etc. }; writer.WriteElement(eb.CreateUnicodeTextRun(new string(hiragana))); writer.WriteElement(eb.CreateTextNewLine()); // CJK Unified Ideographs char[] cjk_uni = { (char)0x5841, (char)0x5842, (char)0x5843, (char)0x5844, (char)0x5845, (char)0x5846, (char)0x5847, (char)0x5848, (char)0x5849, (char)0x584A, (char)0x584B, (char)0x584C, (char)0x584D, (char)0x584E, (char)0x584F, (char)0x5850, (char)0x5851, (char)0x5852 // etc. }; writer.WriteElement(eb.CreateUnicodeTextRun(new string(cjk_uni))); writer.WriteElement(eb.CreateTextNewLine()); // Finish the block of text writer.WriteElement(eb.CreateTextEnd()); writer.End(); // save changes to the current page doc.PagePushBack(page); doc.Save(output_path + "unicodewrite.pdf", SDFDoc.SaveOptions.e_remove_unused | SDFDoc.SaveOptions.e_hex_strings); Console.WriteLine("Done. Result saved in unicodewrite.pdf..."); } } } } catch (PDFNetException e) { Console.WriteLine(e.Message); } }
static void Main(string[] args) { PDFNet.Initialize(); try { using (PDFDoc doc = new PDFDoc()) using (ElementWriter writer = new ElementWriter()) using (ElementBuilder eb = new ElementBuilder()) { // The following sample illustrates how to create and use tiling patterns Page page = doc.PageCreate(); writer.Begin(page); Element element = eb.CreateTextBegin(Font.Create(doc, Font.StandardType1Font.e_times_bold), 1); writer.WriteElement(element); // Begin the text block element = eb.CreateTextRun("G"); element.SetTextMatrix(720, 0, 0, 720, 20, 240); GState gs = element.GetGState(); gs.SetTextRenderMode(GState.TextRenderingMode.e_fill_stroke_text); gs.SetLineWidth(4); // Set the fill color space to the Pattern color space. gs.SetFillColorSpace(ColorSpace.CreatePattern()); gs.SetFillColor(CreateTilingPattern(doc)); writer.WriteElement(element); writer.WriteElement(eb.CreateTextEnd()); // Finish the text block writer.End(); // Save the page doc.PagePushBack(page); //----------------------------------------------- /// The following sample illustrates how to create and use image tiling pattern page = doc.PageCreate(); writer.Begin(page); eb.Reset(); element = eb.CreateRect(0, 0, 612, 794); // Set the fill color space to the Pattern color space. gs = element.GetGState(); gs.SetFillColorSpace(ColorSpace.CreatePattern()); gs.SetFillColor(CreateImageTilingPattern(doc)); element.SetPathFill(true); writer.WriteElement(element); writer.End(); // Save the page doc.PagePushBack(page); //----------------------------------------------- /// The following sample illustrates how to create and use PDF shadings page = doc.PageCreate(); writer.Begin(page); eb.Reset(); element = eb.CreateRect(0, 0, 612, 794); // Set the fill color space to the Pattern color space. gs = element.GetGState(); gs.SetFillColorSpace(ColorSpace.CreatePattern()); gs.SetFillColor(CreateAxialShading(doc)); element.SetPathFill(true); writer.WriteElement(element); writer.End(); // save the page doc.PagePushBack(page); //----------------------------------------------- doc.Save(output_path + "patterns.pdf", SDFDoc.SaveOptions.e_remove_unused); Console.WriteLine("Done. Result saved in patterns.pdf..."); } } catch (PDFNetException e) { Console.WriteLine(e.Message); } }
static void Main(string[] args) { PDFNet.Initialize(); // Relative path to the folder containing test files. string input_path = "../../TestFiles/"; string output_path = "../../TestFiles/Output/"; try { Console.WriteLine("-------------------------------------------------"); Console.WriteLine("Opening the input pdf..."); using (PDFDoc in_doc = new PDFDoc(input_path + "newsletter.pdf")) { in_doc.InitSecurityHandler(); // Create a list of pages to import from one PDF document to another. ArrayList import_list = new ArrayList(); for (PageIterator itr = in_doc.GetPageIterator(); itr.HasNext(); itr.Next()) { import_list.Add(itr.Current()); } using (PDFDoc new_doc = new PDFDoc()) // Create a new document using (ElementBuilder builder = new ElementBuilder()) using (ElementWriter writer = new ElementWriter()) { ArrayList imported_pages = new_doc.ImportPages(import_list); // Paper dimension for A3 format in points. Because one inch has // 72 points, 11.69 inch 72 = 841.69 points Rect media_box = new Rect(0, 0, 1190.88, 841.69); double mid_point = media_box.Width() / 2; for (int i = 0; i < imported_pages.Count; ++i) { // Create a blank new A3 page and place on it two pages from the input document. Page new_page = new_doc.PageCreate(media_box); writer.Begin(new_page); // Place the first page Page src_page = (Page)imported_pages[i]; Element element = builder.CreateForm(src_page); double sc_x = mid_point / src_page.GetPageWidth(); double sc_y = media_box.Height() / src_page.GetPageHeight(); double scale = Math.Min(sc_x, sc_y); element.GetGState().SetTransform(scale, 0, 0, scale, 0, 0); writer.WritePlacedElement(element); // Place the second page ++i; if (i < imported_pages.Count) { src_page = (Page)imported_pages[i]; element = builder.CreateForm(src_page); sc_x = mid_point / src_page.GetPageWidth(); sc_y = media_box.Height() / src_page.GetPageHeight(); scale = Math.Min(sc_x, sc_y); element.GetGState().SetTransform(scale, 0, 0, scale, mid_point, 0); writer.WritePlacedElement(element); } writer.End(); new_doc.PagePushBack(new_page); } new_doc.Save(output_path + "newsletter_booklet.pdf", SDFDoc.SaveOptions.e_linearized); Console.WriteLine("Done. Result saved in newsletter_booklet.pdf..."); } } } catch (Exception e) { Console.WriteLine("Exception caught:\n{0}", e); } }
static void Main(string[] args) { PDFNet.Initialize(); // Relative path to the folder containing test files. // string input_path = "../../TestFiles/"; string output_path = "../../TestFiles/Output/"; // The vector used to store the name and count of all fields. // This is used later on to clone the fields Dictionary <string, int> field_names = new Dictionary <string, int>(); //---------------------------------------------------------------------------------- // Example 1: Programatically create new Form Fields and Widget Annotations. //---------------------------------------------------------------------------------- try { using (PDFDoc doc = new PDFDoc()) { // Create a blank new page and add some form fields. Page blank_page = doc.PageCreate(); // Text Widget Creation // Create an empty text widget with black text. TextWidget text1 = TextWidget.Create(doc, new Rect(110, 700, 380, 730)); text1.SetText("Basic Text Field"); text1.RefreshAppearance(); blank_page.AnnotPushBack(text1); // Create a vertical text widget with blue text and a yellow background. TextWidget text2 = TextWidget.Create(doc, new Rect(50, 400, 90, 730)); text2.SetRotation(90); // Set the text content. text2.SetText(" ****Lucky Stars!****"); // Set the font type, text color, font size, border color and background color. text2.SetFont(Font.Create(doc, Font.StandardType1Font.e_helvetica_oblique)); text2.SetFontSize(28); text2.SetTextColor(new ColorPt(0, 0, 1), 3); text2.SetBorderColor(new ColorPt(0, 0, 0), 3); text2.SetBackgroundColor(new ColorPt(1, 1, 0), 3); text2.RefreshAppearance(); // Add the annotation to the page. blank_page.AnnotPushBack(text2); // Create two new text widget with Field names employee.name.first and employee.name.last // This logic shows how these widgets can be created using either a field name string or // a Field object TextWidget text3 = TextWidget.Create(doc, new Rect(110, 660, 380, 690), "employee.name.first"); text3.SetText("Levi"); text3.SetFont(Font.Create(doc, Font.StandardType1Font.e_times_bold)); text3.RefreshAppearance(); blank_page.AnnotPushBack(text3); Field emp_last_name = doc.FieldCreate("employee.name.last", Field.Type.e_text, "Ackerman"); TextWidget text4 = TextWidget.Create(doc, new Rect(110, 620, 380, 650), emp_last_name); text4.SetFont(Font.Create(doc, Font.StandardType1Font.e_times_bold)); text4.RefreshAppearance(); blank_page.AnnotPushBack(text4); // Signature Widget Creation (unsigned) SignatureWidget signature1 = SignatureWidget.Create(doc, new Rect(110, 560, 260, 610)); signature1.RefreshAppearance(); blank_page.AnnotPushBack(signature1); // CheckBox Widget Creation // Create a check box widget that is not checked. CheckBoxWidget check1 = CheckBoxWidget.Create(doc, new Rect(140, 490, 170, 520)); check1.RefreshAppearance(); blank_page.AnnotPushBack(check1); // Create a check box widget that is checked. CheckBoxWidget check2 = CheckBoxWidget.Create(doc, new Rect(190, 490, 250, 540), "employee.name.check1"); check2.SetBackgroundColor(new ColorPt(1, 1, 1), 3); check2.SetBorderColor(new ColorPt(0, 0, 0), 3); // Check the widget (by default it is unchecked). check2.SetChecked(true); check2.RefreshAppearance(); blank_page.AnnotPushBack(check2); // PushButton Widget Creation PushButtonWidget pushbutton1 = PushButtonWidget.Create(doc, new Rect(380, 490, 520, 540)); pushbutton1.SetTextColor(new ColorPt(1, 1, 1), 3); pushbutton1.SetFontSize(36); pushbutton1.SetBackgroundColor(new ColorPt(0, 0, 0), 3); // Add a caption for the pushbutton. pushbutton1.SetStaticCaptionText("PushButton"); pushbutton1.RefreshAppearance(); blank_page.AnnotPushBack(pushbutton1); // ComboBox Widget Creation ComboBoxWidget combo1 = ComboBoxWidget.Create(doc, new Rect(280, 560, 580, 610)); // Add options to the combobox widget. combo1.AddOption("Combo Box No.1"); combo1.AddOption("Combo Box No.2"); combo1.AddOption("Combo Box No.3"); // Make one of the options in the combo box selected by default. combo1.SetSelectedOption("Combo Box No.2"); combo1.SetTextColor(new ColorPt(1, 0, 0), 3); combo1.SetFontSize(28); combo1.RefreshAppearance(); blank_page.AnnotPushBack(combo1); // ListBox Widget Creation ListBoxWidget list1 = ListBoxWidget.Create(doc, new Rect(400, 620, 580, 730)); // Add one option to the listbox widget. list1.AddOption("List Box No.1"); // Add multiple options to the listbox widget in a batch. string[] list_options = new string[2] { "List Box No.2", "List Box No.3" }; list1.AddOptions(list_options); // Select some of the options in list box as default options list1.SetSelectedOptions(list_options); // Enable list box to have multi-select when editing. list1.GetField().SetFlag(Field.Flag.e_multiselect, true); list1.SetFont(Font.Create(doc, Font.StandardType1Font.e_times_italic)); list1.SetTextColor(new ColorPt(1, 0, 0), 3); list1.SetFontSize(28); list1.SetBackgroundColor(new ColorPt(1, 1, 1), 3); list1.RefreshAppearance(); blank_page.AnnotPushBack(list1); // RadioButton Widget Creation // Create a radio button group and add three radio buttons in it. RadioButtonGroup radio_group = RadioButtonGroup.Create(doc, "RadioGroup"); RadioButtonWidget radiobutton1 = radio_group.Add(new Rect(140, 410, 190, 460)); radiobutton1.SetBackgroundColor(new ColorPt(1, 1, 0), 3); radiobutton1.RefreshAppearance(); RadioButtonWidget radiobutton2 = radio_group.Add(new Rect(310, 410, 360, 460)); radiobutton2.SetBackgroundColor(new ColorPt(0, 1, 0), 3); radiobutton2.RefreshAppearance(); RadioButtonWidget radiobutton3 = radio_group.Add(new Rect(480, 410, 530, 460)); // Enable the third radio button. By default the first one is selected radiobutton3.EnableButton(); radiobutton3.SetBackgroundColor(new ColorPt(0, 1, 1), 3); radiobutton3.RefreshAppearance(); radio_group.AddGroupButtonsToPage(blank_page); // Custom push button annotation creation PushButtonWidget custom_pushbutton1 = PushButtonWidget.Create(doc, new Rect(260, 320, 360, 360)); // Set the annotation appearance. custom_pushbutton1.SetAppearance(CreateCustomButtonAppearance(doc, false), Annot.AnnotationState.e_normal); // Create 'SubmitForm' action. The action will be linked to the button. FileSpec url = FileSpec.CreateURL(doc, "http://www.pdftron.com"); pdftron.PDF.Action button_action = pdftron.PDF.Action.CreateSubmitForm(url); // Associate the above action with 'Down' event in annotations action dictionary. Obj annot_action = custom_pushbutton1.GetSDFObj().PutDict("AA"); annot_action.Put("D", button_action.GetSDFObj()); blank_page.AnnotPushBack(custom_pushbutton1); // Add the page as the last page in the document. doc.PagePushBack(blank_page); // If you are not satisfied with the look of default auto-generated appearance // streams you can delete "AP" entry from the Widget annotation and set // "NeedAppearances" flag in AcroForm dictionary: // doc.GetAcroForm().PutBool("NeedAppearances", true); // This will force the viewer application to auto-generate new appearance streams // every time the document is opened. // // Alternatively you can generate custom annotation appearance using ElementWriter // and then set the "AP" entry in the widget dictionary to the new appearance // stream. // // Yet another option is to pre-populate field entries with dummy text. When // you edit the field values using PDFNet the new field appearances will match // the old ones. doc.RefreshFieldAppearances(); doc.Save(output_path + "forms_test1.pdf", 0); Console.WriteLine("Done."); } } catch (PDFNetException e) { Console.WriteLine(e.Message); } //---------------------------------------------------------------------------------- // Example 2: // Fill-in forms / Modify values of existing fields. // Traverse all form fields in the document (and print out their names). // Search for specific fields in the document. //---------------------------------------------------------------------------------- try { using (PDFDoc doc = new PDFDoc(output_path + "forms_test1.pdf")) { doc.InitSecurityHandler(); FieldIterator itr; for (itr = doc.GetFieldIterator(); itr.HasNext(); itr.Next()) { Field field = itr.Current(); string cur_field_name = field.GetName(); // Add one to the count for this field name for later processing field_names[cur_field_name] = (field_names.ContainsKey(cur_field_name) ? field_names[cur_field_name] + 1 : 1); Console.WriteLine("Field name: {0}", field.GetName()); Console.WriteLine("Field partial name: {0}", field.GetPartialName()); string str_val = field.GetValueAsString(); Console.Write("Field type: "); Field.Type type = field.GetType(); switch (type) { case Field.Type.e_button: Console.WriteLine("Button"); break; case Field.Type.e_radio: Console.WriteLine("Radio button: Value = " + str_val); break; case Field.Type.e_check: field.SetValue(true); Console.WriteLine("Check box: Value = " + str_val); break; case Field.Type.e_text: { Console.WriteLine("Text"); // Edit all variable text in the document String old_value = "none"; if (field.GetValue() != null) { old_value = field.GetValue().GetAsPDFText(); } field.SetValue("This is a new value. The old one was: " + old_value); } break; case Field.Type.e_choice: Console.WriteLine("Choice"); break; case Field.Type.e_signature: Console.WriteLine("Signature"); break; } Console.WriteLine("------------------------------"); } // Search for a specific field Field fld = doc.GetField("employee.name.first"); if (fld != null) { Console.WriteLine("Field search for {0} was successful", fld.GetName()); } else { Console.WriteLine("Field search failed."); } // Regenerate field appearances. doc.RefreshFieldAppearances(); doc.Save(output_path + "forms_test_edit.pdf", 0); Console.WriteLine("Done."); } } catch (PDFNetException e) { Console.WriteLine(e.Message); } //---------------------------------------------------------------------------------- // Sample: Form templating // Replicate pages and form data within a document. Then rename field names to make // them unique. //---------------------------------------------------------------------------------- try { // Sample: Copying the page with forms within the same document using (PDFDoc doc = new PDFDoc(output_path + "forms_test1.pdf")) { doc.InitSecurityHandler(); Page src_page = doc.GetPage(1); doc.PagePushBack(src_page); // Append several copies of the second page doc.PagePushBack(src_page); // Note that forms are successfully copied doc.PagePushBack(src_page); doc.PagePushBack(src_page); // Now we rename fields in order to make every field unique. // You can use this technique for dynamic template filling where you have a 'master' // form page that should be replicated, but with unique field names on every page. foreach (KeyValuePair <string, int> cur_field in field_names) { RenameAllFields(doc, cur_field.Key, cur_field.Value); } doc.Save(output_path + "forms_test1_cloned.pdf", 0); Console.WriteLine("Done."); } } catch (PDFNetException e) { Console.WriteLine(e.Message); } //---------------------------------------------------------------------------------- // Sample: // Flatten all form fields in a document. // Note that this sample is intended to show that it is possible to flatten // individual fields. PDFNet provides a utility function PDFDoc.FlattenAnnotations() // that will automatically flatten all fields. //---------------------------------------------------------------------------------- try { using (PDFDoc doc = new PDFDoc(output_path + "forms_test1.pdf")) { doc.InitSecurityHandler(); bool auto = true; if (auto) { doc.FlattenAnnotations(); } else // Manual flattening { // Traverse all pages PageIterator pitr = doc.GetPageIterator(); for (; pitr.HasNext(); pitr.Next()) { Page page = pitr.Current(); for (int i = page.GetNumAnnots() - 1; i >= 0; --i) { Annot annot = page.GetAnnot(i); if (annot.GetType() == Annot.Type.e_Widget) { annot.Flatten(page); } } } } doc.Save(output_path + "forms_test1_flattened.pdf", 0); Console.WriteLine("Done."); } } catch (PDFNetException e) { Console.WriteLine(e.Message); } }
private static void CreateTestAnnots(PDFDoc doc) { ElementWriter ew = new ElementWriter(); ElementBuilder eb = new ElementBuilder(); Element element; Page first_page = doc.PageCreate(new Rect(0, 0, 600, 600)); doc.PagePushBack(first_page); ew.Begin(first_page, ElementWriter.WriteMode.e_overlay, false); // begin writing to this page ew.End(); // save changes to the current page // // Test of a free text annotation. // { FreeText txtannot = FreeText.Create(doc, new Rect(10, 400, 160, 570)); txtannot.SetContents("\n\nSome swift brown fox snatched a gray hare out of the air by freezing it with an angry glare." + "\n\nAha!\n\nAnd there was much rejoicing!"); txtannot.SetBorderStyle(new Annot.BorderStyle(Annot.BorderStyle.Style.e_solid, 1, 10, 20)); txtannot.SetQuaddingFormat(0); first_page.AnnotPushBack(txtannot); txtannot.RefreshAppearance(); } { FreeText txtannot = FreeText.Create(doc, new Rect(100, 100, 350, 500)); txtannot.SetContentRect(new Rect(200, 200, 350, 500)); txtannot.SetContents("\n\nSome swift brown fox snatched a gray hare out of the air by freezing it with an angry glare." + "\n\nAha!\n\nAnd there was much rejoicing!"); txtannot.SetCalloutLinePoints(new Point(200, 300), new Point(150, 290), new Point(110, 110)); txtannot.SetBorderStyle(new Annot.BorderStyle(Annot.BorderStyle.Style.e_solid, 1, 10, 20)); txtannot.SetEndingStyle(Line.EndingStyle.e_ClosedArrow); txtannot.SetColor(new ColorPt(0, 1, 0)); txtannot.SetQuaddingFormat(1); first_page.AnnotPushBack(txtannot); txtannot.RefreshAppearance(); } { FreeText txtannot = FreeText.Create(doc, new Rect(400, 10, 550, 400)); txtannot.SetContents("\n\nSome swift brown fox snatched a gray hare out of the air by freezing it with an angry glare." + "\n\nAha!\n\nAnd there was much rejoicing!"); txtannot.SetBorderStyle(new Annot.BorderStyle(Annot.BorderStyle.Style.e_solid, 1, 10, 20)); txtannot.SetColor(new ColorPt(0, 0, 1)); txtannot.SetOpacity(0.2); txtannot.SetQuaddingFormat(2); first_page.AnnotPushBack(txtannot); txtannot.RefreshAppearance(); } Page page = doc.PageCreate(new Rect(0, 0, 600, 600)); doc.PagePushBack(page); ew.Begin(page, ElementWriter.WriteMode.e_overlay, false); // begin writing to this page eb.Reset(); // Reset the GState to default ew.End(); // save changes to the current page { //Create a Line annotation... Line line = Line.Create(doc, new Rect(250, 250, 400, 400)); line.SetStartPoint(new Point(350, 270)); line.SetEndPoint(new Point(260, 370)); line.SetStartStyle(Line.EndingStyle.e_Square); line.SetEndStyle(Line.EndingStyle.e_Circle); line.SetColor(new ColorPt(.3, .5, 0), 3); line.SetContents("Dashed Captioned"); line.SetShowCaption(true); line.SetCaptionPosition(Line.CapPos.e_Top); double[] dash = new double[2]; dash[0] = 2; dash[1] = 2.0; line.SetBorderStyle(new Annot.BorderStyle(Annot.BorderStyle.Style.e_dashed, 2, 0, 0, dash)); line.RefreshAppearance(); page.AnnotPushBack(line); } { Line line = Line.Create(doc, new Rect(347, 377, 600, 600)); line.SetStartPoint(new Point(385, 410)); line.SetEndPoint(new Point(540, 555)); line.SetStartStyle(Line.EndingStyle.e_Circle); line.SetEndStyle(Line.EndingStyle.e_OpenArrow); line.SetColor(new ColorPt(1, 0, 0), 3); line.SetInteriorColor(new ColorPt(0, 1, 0), 3); line.SetContents("Inline Caption"); line.SetShowCaption(true); line.SetCaptionPosition(Line.CapPos.e_Inline); line.SetLeaderLineExtensionLength(-4); line.SetLeaderLineLength(-12); line.SetLeaderLineOffset(2); line.RefreshAppearance(); page.AnnotPushBack(line); } { Line line = Line.Create(doc, new Rect(10, 400, 200, 600)); line.SetStartPoint(new Point(25, 426)); line.SetEndPoint(new Point(180, 555)); line.SetStartStyle(Line.EndingStyle.e_Circle); line.SetEndStyle(Line.EndingStyle.e_Square); line.SetColor(new ColorPt(0, 0, 1), 3); line.SetInteriorColor(new ColorPt(1, 0, 0), 3); line.SetContents("Offset Caption"); line.SetShowCaption(true); line.SetCaptionPosition(Line.CapPos.e_Top); line.SetTextHOffset(-60); line.SetTextVOffset(10); line.RefreshAppearance(); page.AnnotPushBack(line); } { Line line = Line.Create(doc, new Rect(200, 10, 400, 70)); line.SetStartPoint(new Point(220, 25)); line.SetEndPoint(new Point(370, 60)); line.SetStartStyle(Line.EndingStyle.e_Butt); line.SetEndStyle(Line.EndingStyle.e_OpenArrow); line.SetColor(new ColorPt(0, 0, 1), 3); line.SetContents("Regular Caption"); line.SetShowCaption(true); line.SetCaptionPosition(Line.CapPos.e_Top); line.RefreshAppearance(); page.AnnotPushBack(line); } { Line line = Line.Create(doc, new Rect(200, 70, 400, 130)); line.SetStartPoint(new Point(220, 111)); line.SetEndPoint(new Point(370, 78)); line.SetStartStyle(Line.EndingStyle.e_Circle); line.SetEndStyle(Line.EndingStyle.e_Diamond); line.SetContents("Circle to Diamond"); line.SetColor(new ColorPt(0, 0, 1), 3); line.SetInteriorColor(new ColorPt(0, 1, 0), 3); line.SetShowCaption(true); line.SetCaptionPosition(Line.CapPos.e_Top); line.RefreshAppearance(); page.AnnotPushBack(line); } { Line line = Line.Create(doc, new Rect(10, 100, 160, 200)); line.SetStartPoint(new Point(15, 110)); line.SetEndPoint(new Point(150, 190)); line.SetStartStyle(Line.EndingStyle.e_Slash); line.SetEndStyle(Line.EndingStyle.e_ClosedArrow); line.SetContents("Slash to CArrow"); line.SetColor(new ColorPt(1, 0, 0), 3); line.SetInteriorColor(new ColorPt(0, 1, 1), 3); line.SetShowCaption(true); line.SetCaptionPosition(Line.CapPos.e_Top); line.RefreshAppearance(); page.AnnotPushBack(line); } { Line line = Line.Create(doc, new Rect(270, 270, 570, 433)); line.SetStartPoint(new Point(300, 400)); line.SetEndPoint(new Point(550, 300)); line.SetStartStyle(Line.EndingStyle.e_RClosedArrow); line.SetEndStyle(Line.EndingStyle.e_ROpenArrow); line.SetContents("ROpen & RClosed arrows"); line.SetColor(new ColorPt(0, 0, 1), 3); line.SetInteriorColor(new ColorPt(0, 1, 0), 3); line.SetShowCaption(true); line.SetCaptionPosition(Line.CapPos.e_Top); line.RefreshAppearance(); page.AnnotPushBack(line); } { Line line = Line.Create(doc, new Rect(195, 395, 205, 505)); line.SetStartPoint(new Point(200, 400)); line.SetEndPoint(new Point(200, 500)); line.RefreshAppearance(); page.AnnotPushBack(line); } { Line line = Line.Create(doc, new Rect(55, 299, 150, 301)); line.SetStartPoint(new Point(55, 300)); line.SetEndPoint(new Point(155, 300)); line.SetStartStyle(Line.EndingStyle.e_Circle); line.SetEndStyle(Line.EndingStyle.e_Circle); line.SetContents("Caption that's longer than its line."); line.SetColor(new ColorPt(1, 0, 1), 3); line.SetInteriorColor(new ColorPt(0, 1, 0), 3); line.SetShowCaption(true); line.SetCaptionPosition(Line.CapPos.e_Top); line.RefreshAppearance(); page.AnnotPushBack(line); } { Line line = Line.Create(doc, new Rect(300, 200, 390, 234)); line.SetStartPoint(new Point(310, 210)); line.SetEndPoint(new Point(380, 220)); line.SetColor(new ColorPt(0, 0, 0), 3); line.RefreshAppearance(); page.AnnotPushBack(line); } Page page3 = doc.PageCreate(new Rect(0, 0, 600, 600)); ew.Begin(page3); // begin writing to the page ew.End(); // save changes to the current page doc.PagePushBack(page3); { Circle circle = Circle.Create(doc, new Rect(300, 300, 390, 350)); circle.SetColor(new ColorPt(0, 0, 0), 3); circle.RefreshAppearance(); page3.AnnotPushBack(circle); } { Circle circle = Circle.Create(doc, new Rect(100, 100, 200, 200)); circle.SetColor(new ColorPt(0, 1, 0), 3); circle.SetInteriorColor(new ColorPt(0, 0, 1), 3); double[] dash = new double[2]; dash[0] = 2; dash[1] = 4; circle.SetBorderStyle(new Annot.BorderStyle(Annot.BorderStyle.Style.e_dashed, 3, 0, 0, dash)); circle.SetPadding(new Rect(2, 2, 2, 2)); circle.RefreshAppearance(); page3.AnnotPushBack(circle); } { Square sq = Square.Create(doc, new Rect(10, 200, 80, 300)); sq.SetColor(new ColorPt(0, 0, 0), 3); sq.RefreshAppearance(); page3.AnnotPushBack(sq); } { Square sq = Square.Create(doc, new Rect(500, 200, 580, 300)); sq.SetColor(new ColorPt(1, 0, 0), 3); sq.SetInteriorColor(new ColorPt(0, 1, 1), 3); double[] dash = new double[2]; dash[0] = 4; dash[1] = 2; sq.SetBorderStyle(new Annot.BorderStyle(Annot.BorderStyle.Style.e_dashed, 6, 0, 0, dash)); sq.SetPadding(new Rect(4, 4, 4, 4)); sq.RefreshAppearance(); page3.AnnotPushBack(sq); } { Polygon poly = Polygon.Create(doc, new Rect(5, 500, 125, 590)); poly.SetColor(new ColorPt(1, 0, 0), 3); poly.SetInteriorColor(new ColorPt(1, 1, 0), 3); poly.SetVertex(0, new Point(12, 510)); poly.SetVertex(1, new Point(100, 510)); poly.SetVertex(2, new Point(100, 555)); poly.SetVertex(3, new Point(35, 544)); poly.SetBorderStyle(new Annot.BorderStyle(Annot.BorderStyle.Style.e_solid, 4, 0, 0)); poly.SetPadding(new Rect(4, 4, 4, 4)); poly.RefreshAppearance(); page3.AnnotPushBack(poly); } { PolyLine poly = PolyLine.Create(doc, new Rect(400, 10, 500, 90)); poly.SetColor(new ColorPt(1, 0, 0), 3); poly.SetInteriorColor(new ColorPt(0, 1, 0), 3); poly.SetVertex(0, new Point(405, 20)); poly.SetVertex(1, new Point(440, 40)); poly.SetVertex(2, new Point(410, 60)); poly.SetVertex(3, new Point(470, 80)); poly.SetBorderStyle(new Annot.BorderStyle(Annot.BorderStyle.Style.e_solid, 2, 0, 0)); poly.SetPadding(new Rect(4, 4, 4, 4)); poly.SetStartStyle(Line.EndingStyle.e_RClosedArrow); poly.SetEndStyle(Line.EndingStyle.e_ClosedArrow); poly.RefreshAppearance(); page3.AnnotPushBack(poly); } { Link lk = Link.Create(doc, new Rect(5, 5, 55, 24)); //lk.SetColor( ColorPt(0,1,0), 3 ); lk.RefreshAppearance(); page3.AnnotPushBack(lk); } Page page4 = doc.PageCreate(new Rect(0, 0, 600, 600)); ew.Begin(page4); // begin writing to the page ew.End(); // save changes to the current page doc.PagePushBack(page4); { ew.Begin(page4); Font font = Font.Create(doc, Font.StandardType1Font.e_helvetica); element = eb.CreateTextBegin(font, 16); element.SetPathFill(true); ew.WriteElement(element); element = eb.CreateTextRun("Some random text on the page", font, 16); element.SetTextMatrix(1, 0, 0, 1, 100, 500); ew.WriteElement(element); ew.WriteElement(eb.CreateTextEnd()); ew.End(); } { Highlight hl = Highlight.Create(doc, new Rect(100, 490, 150, 515)); hl.SetColor(new ColorPt(0, 1, 0), 3); hl.RefreshAppearance(); page4.AnnotPushBack(hl); } { Squiggly sq = Squiggly.Create(doc, new Rect(100, 450, 250, 600)); //sq.SetColor( ColorPt(1,0,0), 3 ); sq.SetQuadPoint(0, new QuadPoint(new Point(122, 455), new Point(240, 545), new Point(230, 595), new Point(101, 500))); sq.RefreshAppearance(); page4.AnnotPushBack(sq); } { Caret cr = Caret.Create(doc, new Rect(100, 40, 129, 69)); cr.SetColor(new ColorPt(0, 0, 1), 3); cr.SetSymbol("P"); cr.RefreshAppearance(); page4.AnnotPushBack(cr); } Page page5 = doc.PageCreate(new Rect(0, 0, 600, 600)); ew.Begin(page5); // begin writing to the page ew.End(); // save changes to the current page doc.PagePushBack(page5); Page page6 = doc.PageCreate(new Rect(0, 0, 600, 600)); ew.Begin(page6); // begin writing to the page ew.End(); // save changes to the current page doc.PagePushBack(page6); { Text txt = Text.Create(doc, new Rect(10, 20, 30, 40)); txt.SetIcon("UserIcon"); txt.SetContents("User defined icon, unrecognized by appearance generator"); txt.SetColor(new ColorPt(0, 1, 0)); txt.RefreshAppearance(); page6.AnnotPushBack(txt); } { Ink ink = Ink.Create(doc, new Rect(100, 400, 200, 550)); ink.SetColor(new ColorPt(0, 0, 1)); ink.SetPoint(1, 3, new Point(220, 505)); ink.SetPoint(1, 0, new Point(100, 490)); ink.SetPoint(0, 1, new Point(120, 410)); ink.SetPoint(0, 0, new Point(100, 400)); ink.SetPoint(1, 2, new Point(180, 490)); ink.SetPoint(1, 1, new Point(140, 440)); ink.SetBorderStyle(new Annot.BorderStyle(Annot.BorderStyle.Style.e_solid, 3, 0, 0)); ink.RefreshAppearance(); page6.AnnotPushBack(ink); } Page page7 = doc.PageCreate(new Rect(0, 0, 600, 600)); ew.Begin(page7); // begin writing to the page ew.End(); // save changes to the current page doc.PagePushBack(page7); { Sound snd = Sound.Create(doc, new Rect(100, 500, 120, 520)); snd.SetColor(new ColorPt(1, 1, 0)); snd.SetIcon(Sound.Icon.e_Speaker); snd.RefreshAppearance(); page7.AnnotPushBack(snd); } { Sound snd = Sound.Create(doc, new Rect(200, 500, 220, 520)); snd.SetColor(new ColorPt(1, 1, 0)); snd.SetIcon(Sound.Icon.e_Mic); snd.RefreshAppearance(); page7.AnnotPushBack(snd); } Page page8 = doc.PageCreate(new Rect(0, 0, 600, 600)); ew.Begin(page8); // begin writing to the page ew.End(); // save changes to the current page doc.PagePushBack(page8); for (int ipage = 0; ipage < 2; ++ipage) { double px = 5, py = 520; for (RubberStamp.Icon istamp = RubberStamp.Icon.e_Approved; istamp <= RubberStamp.Icon.e_Draft; istamp = (RubberStamp.Icon)((int)(istamp) + 1)) { RubberStamp stmp = RubberStamp.Create(doc, new Rect(1, 1, 100, 100)); stmp.SetIcon(istamp); stmp.SetContents(stmp.GetIconName()); stmp.SetRect(new Rect(px, py, px + 100, py + 25)); py -= 100; if (py < 0) { py = 520; px += 200; } if (ipage == 0) { //page7.AnnotPushBack( st ); ; } else { page8.AnnotPushBack(stmp); stmp.RefreshAppearance(); } } } RubberStamp st = RubberStamp.Create(doc, new Rect(400, 5, 550, 45)); st.SetIcon("UserStamp"); st.SetContents("User defined stamp"); page8.AnnotPushBack(st); st.RefreshAppearance(); }
static void Main(string[] args) { PDFNet.Initialize(); // Relative path to the folder containing test files. string input_path = "../../TestFiles/"; string output_path = "../../TestFiles/Output/"; // Sample 1 - Split a PDF document into multiple pages try { Console.WriteLine("_______________________________________________"); Console.WriteLine("Sample 1 - Split a PDF document into multiple pages..."); Console.WriteLine("Opening the input pdf..."); using (PDFDoc in_doc = new PDFDoc(input_path + "newsletter.pdf")) { in_doc.InitSecurityHandler(); int page_num = in_doc.GetPageCount(); for (int i = 1; i <= page_num; ++i) { using (PDFDoc new_doc = new PDFDoc()) { new_doc.InsertPages(0, in_doc, i, i, PDFDoc.InsertFlag.e_none); new_doc.Save(output_path + "newsletter_split_page_" + i + ".pdf", SDFDoc.SaveOptions.e_remove_unused); Console.WriteLine("Done. Result saved in newsletter_split_page_" + i + ".pdf"); } } } } catch (Exception e) { Console.WriteLine("Exception caught:\n{0}", e); } // Sample 2 - Merge several PDF documents into one try { Console.WriteLine("_______________________________________________"); Console.WriteLine("Sample 2 - Merge several PDF documents into one..."); using (PDFDoc new_doc = new PDFDoc()) { new_doc.InitSecurityHandler(); int page_num = 15; for (int i = 1; i <= page_num; ++i) { Console.WriteLine("Opening newsletter_split_page_" + i + ".pdf"); using (PDFDoc in_doc = new PDFDoc(output_path + "newsletter_split_page_" + i + ".pdf")) { new_doc.InsertPages(i, in_doc, 1, in_doc.GetPageCount(), PDFDoc.InsertFlag.e_none); } } new_doc.Save(output_path + "newsletter_merge_pages.pdf", SDFDoc.SaveOptions.e_remove_unused); } Console.WriteLine("Done. Result saved in newsletter_merge_pages.pdf"); } catch (Exception e) { Console.WriteLine("Exception caught:\n{0}", e); } // Sample 3 - Delete every second page try { Console.WriteLine("_______________________________________________"); Console.WriteLine("Sample 3 - Delete every second page..."); Console.WriteLine("Opening the input pdf..."); using (PDFDoc in_doc = new PDFDoc(input_path + "newsletter.pdf")) { in_doc.InitSecurityHandler(); int page_num = in_doc.GetPageCount(); PageIterator itr; while (page_num >= 1) { itr = in_doc.GetPageIterator(page_num); in_doc.PageRemove(itr); page_num -= 2; } in_doc.Save(output_path + "newsletter_page_remove.pdf", 0); } Console.WriteLine("Done. Result saved in newsletter_page_remove.pdf..."); } catch (Exception e) { Console.WriteLine("Exception caught:\n{0}", e); } // Sample 4 - Inserts a page from one document at different // locations within another document try { Console.WriteLine("_______________________________________________"); Console.WriteLine("Sample 4 - Insert a page at different locations..."); Console.WriteLine("Opening the input pdf..."); using (PDFDoc in1_doc = new PDFDoc(input_path + "newsletter.pdf")) using (PDFDoc in2_doc = new PDFDoc(input_path + "fish.pdf")) { in1_doc.InitSecurityHandler(); in2_doc.InitSecurityHandler(); Page src_page = in2_doc.GetPage(1); PageIterator dst_page = in1_doc.GetPageIterator(1); int page_num = 1; while (dst_page.HasNext()) { if (page_num++ % 3 == 0) { in1_doc.PageInsert(dst_page, src_page); } dst_page.Next(); } in1_doc.Save(output_path + "newsletter_page_insert.pdf", 0); Console.WriteLine("Done. Result saved in newsletter_page_insert.pdf..."); } } catch (Exception e) { Console.WriteLine("Exception caught:\n{0}", e); } // Sample 5 - Replicate pages within a single document try { Console.WriteLine("_______________________________________________"); Console.WriteLine("Sample 5 - Replicate pages within a single document..."); Console.WriteLine("Opening the input pdf..."); using (PDFDoc doc = new PDFDoc(input_path + "newsletter.pdf")) { doc.InitSecurityHandler(); // Replicate the cover page three times (copy page #1 and place it before the // seventh page in the document page sequence) Page cover = doc.GetPage(1); PageIterator p7 = doc.GetPageIterator(7); doc.PageInsert(p7, cover); doc.PageInsert(p7, cover); doc.PageInsert(p7, cover); // Replicate the cover page two more times by placing it before and after // existing pages. doc.PagePushFront(cover); doc.PagePushBack(cover); doc.Save(output_path + "newsletter_page_clone.pdf", 0); Console.WriteLine("Done. Result saved in newsletter_page_clone.pdf..."); } } catch (Exception e) { Console.WriteLine("Exception caught:\n{0}", e); } // Sample 6 - Use ImportPages() in order to copy multiple pages at once // in order to preserve shared resources between pages (e.g. images, fonts, // colorspaces, etc.) try { Console.WriteLine("_______________________________________________"); Console.WriteLine("Sample 6 - Preserving shared resources using ImportPages..."); Console.WriteLine("Opening the input pdf..."); using (PDFDoc in_doc = new PDFDoc(input_path + "newsletter.pdf")) { in_doc.InitSecurityHandler(); using (PDFDoc new_doc = new PDFDoc()) { ArrayList copy_pages = new ArrayList(); for (PageIterator itr = in_doc.GetPageIterator(); itr.HasNext(); itr.Next()) { copy_pages.Add(itr.Current()); } ArrayList imported_pages = new_doc.ImportPages(copy_pages); for (int i = 0; i != imported_pages.Count; ++i) { new_doc.PagePushFront((Page)imported_pages[i]); // Order pages in reverse order. // Use PagePushBack() if you would like to preserve the same order. } new_doc.Save(output_path + "newsletter_import_pages.pdf", 0); Console.WriteLine("Done. Result saved in newsletter_import_pages.pdf..."); Console.WriteLine(); Console.WriteLine("Note that the output file size is less than half the size"); Console.WriteLine("of the file produced using individual page copy operations"); Console.WriteLine("between two documents"); } } } catch (Exception e) { Console.WriteLine("Exception caught:\n{0}", e); } }
static void Main(string[] args) { PDFNet.Initialize(); try { using (PDFDoc doc = new PDFDoc()) using (ElementBuilder builder = new ElementBuilder()) // ElementBuilder is used to build new Element objects using (ElementWriter writer = new ElementWriter()) // ElementWriter is used to write Elements to the page { // Create three layers... Group image_layer = CreateLayer(doc, "Image Layer"); Group text_layer = CreateLayer(doc, "Text Layer"); Group vector_layer = CreateLayer(doc, "Vector Layer"); // Start a new page ------------------------------------ Page page = doc.PageCreate(); writer.Begin(page); // begin writing to this page // Add new content to the page and associate it with one of the layers. Element element = builder.CreateForm(CreateGroup1(doc, image_layer.GetSDFObj())); writer.WriteElement(element); element = builder.CreateForm(CreateGroup2(doc, vector_layer.GetSDFObj())); writer.WriteElement(element); // Add the text layer to the page... bool enableOCMD = false; // set to 'true' to enable 'ocmd' example. if (enableOCMD) { // A bit more advanced example of how to create an OCMD text layer that // is visible only if text, image and path layers are all 'ON'. // An example of how to set 'Visibility Policy' in OCMD. Obj ocgs = doc.CreateIndirectArray(); ocgs.PushBack(image_layer.GetSDFObj()); ocgs.PushBack(vector_layer.GetSDFObj()); ocgs.PushBack(text_layer.GetSDFObj()); OCMD text_ocmd = OCMD.Create(doc, ocgs, OCMD.VisibilityPolicyType.e_AllOn); element = builder.CreateForm(CreateGroup3(doc, text_ocmd.GetSDFObj())); } else { element = builder.CreateForm(CreateGroup3(doc, text_layer.GetSDFObj())); } writer.WriteElement(element); // Add some content to the page that does not belong to any layer... // In this case this is a rectangle representing the page border. element = builder.CreateRect(0, 0, page.GetPageWidth(), page.GetPageHeight()); element.SetPathFill(false); element.SetPathStroke(true); element.GetGState().SetLineWidth(40); writer.WriteElement(element); writer.End(); // save changes to the current page doc.PagePushBack(page); // Set the default viewing preference to display 'Layer' tab. PDFDocViewPrefs prefs = doc.GetViewPrefs(); prefs.SetPageMode(PDFDocViewPrefs.PageMode.e_UseOC); doc.Save(output_path + "pdf_layers.pdf", SDFDoc.SaveOptions.e_linearized); Console.WriteLine("Done."); } } catch (PDFNetException e) { Console.WriteLine(e.Message); } // The following is a code snippet shows how to selectively render // and export PDF layers. try { using (PDFDoc doc = new PDFDoc(output_path + "pdf_layers.pdf")) { doc.InitSecurityHandler(); if (!doc.HasOC()) { Console.WriteLine("The document does not contain 'Optional Content'"); } else { Config init_cfg = doc.GetOCGConfig(); Context ctx = new Context(init_cfg); using (PDFDraw pdfdraw = new PDFDraw()) { pdfdraw.SetImageSize(1000, 1000); pdfdraw.SetOCGContext(ctx); // Render the page using the given OCG context. Page page = doc.GetPage(1); // Get the first page in the document. pdfdraw.Export(page, output_path + "pdf_layers_default.png"); // Disable drawing of content that is not optional (i.e. is not part of any layer). ctx.SetNonOCDrawing(false); // Now render each layer in the input document to a separate image. Obj ocgs = doc.GetOCGs(); // Get the array of all OCGs in the document. if (ocgs != null) { int i, sz = ocgs.Size(); for (i = 0; i < sz; ++i) { Group ocg = new Group(ocgs.GetAt(i)); ctx.ResetStates(false); ctx.SetState(ocg, true); string fname = "pdf_layers_" + ocg.GetName() + ".png"; Console.WriteLine(fname); pdfdraw.Export(page, fname); } } // Now draw content that is not part of any layer... ctx.SetNonOCDrawing(true); ctx.SetOCDrawMode(Context.OCDrawMode.e_NoOC); pdfdraw.Export(page, output_path + "pdf_layers_non_oc.png"); Console.WriteLine("Done."); } } } } catch (PDFNetException e) { Console.WriteLine(e.Message); } }
static void Main(string[] args) { PDFNet.Initialize(); // Relative path to the folder containing test files. string input_path = "../../TestFiles/"; string output_path = "../../TestFiles/Output/"; try { using (PDFDoc doc = new PDFDoc()) using (ElementBuilder eb = new ElementBuilder()) // ElementBuilder is used to build new Element objects using (ElementWriter writer = new ElementWriter()) // ElementWriter is used to write Elements to the page { // Start a new page ------------------------------------ // Position an image stream on several places on the page Page page = doc.PageCreate(new Rect(0, 0, 612, 794)); writer.Begin(page); // begin writing to this page // Create an Image that can be reused multiple times in the document or // multiple on the same page. MappedFile img_file = new MappedFile(input_path + "peppers.jpg"); FilterReader img_data = new FilterReader(img_file); Image img = Image.Create(doc, img_data, 400, 600, 8, ColorSpace.CreateDeviceRGB(), Image.InputFilter.e_jpeg); Element element = eb.CreateImage(img, new Matrix2D(200, -145, 20, 300, 200, 150)); writer.WritePlacedElement(element); GState gstate = element.GetGState(); // use the same image (just change its matrix) gstate.SetTransform(200, 0, 0, 300, 50, 450); writer.WritePlacedElement(element); // use the same image again (just change its matrix). writer.WritePlacedElement(eb.CreateImage(img, 300, 600, 200, -150)); writer.End(); // save changes to the current page doc.PagePushBack(page); // Start a new page ------------------------------------ // Construct and draw a path object using different styles page = doc.PageCreate(new Rect(0, 0, 612, 794)); writer.Begin(page); // begin writing to this page eb.Reset(); // Reset GState to default eb.PathBegin(); // start constructing the path eb.MoveTo(306, 396); eb.CurveTo(681, 771, 399.75, 864.75, 306, 771); eb.CurveTo(212.25, 864.75, -69, 771, 306, 396); eb.ClosePath(); element = eb.PathEnd(); // the path is now finished element.SetPathFill(true); // the path should be filled // Set the path color space and color gstate = element.GetGState(); gstate.SetFillColorSpace(ColorSpace.CreateDeviceCMYK()); gstate.SetFillColor(new ColorPt(1, 0, 0, 0)); // cyan gstate.SetTransform(0.5, 0, 0, 0.5, -20, 300); writer.WritePlacedElement(element); // Draw the same path using a different stroke color element.SetPathStroke(true); // this path is should be filled and stroked gstate.SetFillColor(new ColorPt(0, 0, 1, 0)); // yellow gstate.SetStrokeColorSpace(ColorSpace.CreateDeviceRGB()); gstate.SetStrokeColor(new ColorPt(1, 0, 0)); // red gstate.SetTransform(0.5, 0, 0, 0.5, 280, 300); gstate.SetLineWidth(20); writer.WritePlacedElement(element); // Draw the same path with with a given dash pattern element.SetPathFill(false); // this path is should be only stroked gstate.SetStrokeColor(new ColorPt(0, 0, 1)); // blue gstate.SetTransform(0.5, 0, 0, 0.5, 280, 0); double[] dash_pattern = { 30 }; gstate.SetDashPattern(dash_pattern, 0); writer.WritePlacedElement(element); // Use the path as a clipping path writer.WriteElement(eb.CreateGroupBegin()); // Save the graphics state // Start constructing a new path (the old path was lost when we created // a new Element using CreateGroupBegin()). eb.PathBegin(); eb.MoveTo(306, 396); eb.CurveTo(681, 771, 399.75, 864.75, 306, 771); eb.CurveTo(212.25, 864.75, -69, 771, 306, 396); eb.ClosePath(); element = eb.PathEnd(); // path is now built element.SetPathClip(true); // this path is a clipping path element.SetPathStroke(true); // this path is should be filled and stroked gstate = element.GetGState(); gstate.SetTransform(0.5, 0, 0, 0.5, -20, 0); writer.WriteElement(element); writer.WriteElement(eb.CreateImage(img, 100, 300, 400, 600)); writer.WriteElement(eb.CreateGroupEnd()); // Restore the graphics state writer.End(); // save changes to the current page doc.PagePushBack(page); // Start a new page ------------------------------------ page = doc.PageCreate(new Rect(0, 0, 612, 794)); writer.Begin(page); // begin writing to this page eb.Reset(); // Reset GState to default // Begin writing a block of text element = eb.CreateTextBegin(Font.Create(doc, Font.StandardType1Font.e_times_roman), 12); writer.WriteElement(element); string data = "Hello World!"; element = eb.CreateTextRun(data); element.SetTextMatrix(10, 0, 0, 10, 0, 600); element.GetGState().SetLeading(15); // Set the spacing between lines writer.WriteElement(element); writer.WriteElement(eb.CreateTextNewLine()); // New line element = eb.CreateTextRun(data); gstate = element.GetGState(); gstate.SetTextRenderMode(GState.TextRenderingMode.e_stroke_text); gstate.SetCharSpacing(-1.25); gstate.SetWordSpacing(-1.25); writer.WriteElement(element); writer.WriteElement(eb.CreateTextNewLine()); // New line element = eb.CreateTextRun(data); gstate = element.GetGState(); gstate.SetCharSpacing(0); gstate.SetWordSpacing(0); gstate.SetLineWidth(3); gstate.SetTextRenderMode(GState.TextRenderingMode.e_fill_stroke_text); gstate.SetStrokeColorSpace(ColorSpace.CreateDeviceRGB()); gstate.SetStrokeColor(new ColorPt(1, 0, 0)); // red gstate.SetFillColorSpace(ColorSpace.CreateDeviceCMYK()); gstate.SetFillColor(new ColorPt(1, 0, 0, 0)); // cyan writer.WriteElement(element); writer.WriteElement(eb.CreateTextNewLine()); // New line // Set text as a clipping path to the image. element = eb.CreateTextRun(data); gstate = element.GetGState(); gstate.SetTextRenderMode(GState.TextRenderingMode.e_clip_text); writer.WriteElement(element); // Finish the block of text writer.WriteElement(eb.CreateTextEnd()); // Draw an image that will be clipped by the above text writer.WriteElement(eb.CreateImage(img, 10, 100, 1300, 720)); writer.End(); // save changes to the current page doc.PagePushBack(page); // Start a new page ------------------------------------ // // The example illustrates how to embed the external font in a PDF document. // The example also shows how ElementReader can be used to copy and modify // Elements between pages. using (ElementReader reader = new ElementReader()) { // Start reading Elements from the last page. We will copy all Elements to // a new page but will modify the font associated with text. reader.Begin(doc.GetPage(doc.GetPageCount())); page = doc.PageCreate(new Rect(0, 0, 1300, 794)); writer.Begin(page); // begin writing to this page eb.Reset(); // Reset GState to default // Embed an external font in the document. Font font = Font.CreateTrueTypeFont(doc, input_path + "font.ttf"); while ((element = reader.Next()) != null) // Read page contents { if (element.GetType() == Element.Type.e_text) { element.GetGState().SetFont(font, 12); } writer.WriteElement(element); } reader.End(); writer.End(); // save changes to the current page doc.PagePushBack(page); // Start a new page ------------------------------------ // // The example illustrates how to embed the external font in a PDF document. // The example also shows how ElementReader can be used to copy and modify // Elements between pages. // Start reading Elements from the last page. We will copy all Elements to // a new page but will modify the font associated with text. reader.Begin(doc.GetPage(doc.GetPageCount())); page = doc.PageCreate(new Rect(0, 0, 1300, 794)); writer.Begin(page); // begin writing to this page eb.Reset(); // Reset GState to default // Embed an external font in the document. Font font2 = Font.CreateType1Font(doc, input_path + "Misc-Fixed.pfa"); while ((element = reader.Next()) != null) // Read page contents { if (element.GetType() == Element.Type.e_text) { element.GetGState().SetFont(font2, 12); } writer.WriteElement(element); } reader.End(); writer.End(); // save changes to the current page doc.PagePushBack(page); // Start a new page ------------------------------------ page = doc.PageCreate(); writer.Begin(page); // begin writing to this page eb.Reset(); // Reset GState to default // Begin writing a block of text element = eb.CreateTextBegin(Font.Create(doc, Font.StandardType1Font.e_times_roman), 12); element.SetTextMatrix(1.5, 0, 0, 1.5, 50, 600); element.GetGState().SetLeading(15); // Set the spacing between lines writer.WriteElement(element); string para = "A PDF text object consists of operators that can show " + "text strings, move the text position, and set text state and certain " + "other parameters. In addition, there are three parameters that are " + "defined only within a text object and do not persist from one text " + "object to the next: Tm, the text matrix, Tlm, the text line matrix, " + "Trm, the text rendering matrix, actually just an intermediate result " + "that combines the effects of text state parameters, the text matrix " + "(Tm), and the current transformation matrix"; int para_end = para.Length; int text_run = 0; int text_run_end; double para_width = 300; // paragraph width is 300 units double cur_width = 0; while (text_run < para_end) { text_run_end = para.IndexOf(' ', text_run); if (text_run_end < 0) { text_run_end = para_end - 1; } string text = para.Substring(text_run, text_run_end - text_run + 1); element = eb.CreateTextRun(text); if (cur_width + element.GetTextLength() < para_width) { writer.WriteElement(element); cur_width += element.GetTextLength(); } else { writer.WriteElement(eb.CreateTextNewLine()); // New line text = para.Substring(text_run, text_run_end - text_run + 1); element = eb.CreateTextRun(text); cur_width = element.GetTextLength(); writer.WriteElement(element); } text_run = text_run_end + 1; } // ----------------------------------------------------------------------- // The following code snippet illustrates how to adjust spacing between // characters (text runs). element = eb.CreateTextNewLine(); writer.WriteElement(element); // Skip 2 lines writer.WriteElement(element); writer.WriteElement(eb.CreateTextRun("An example of space adjustments between inter-characters:")); writer.WriteElement(eb.CreateTextNewLine()); // Write string "AWAY" without space adjustments between characters. element = eb.CreateTextRun("AWAY"); writer.WriteElement(element); writer.WriteElement(eb.CreateTextNewLine()); // Write string "AWAY" with space adjustments between characters. element = eb.CreateTextRun("A"); writer.WriteElement(element); element = eb.CreateTextRun("W"); element.SetPosAdjustment(140); writer.WriteElement(element); element = eb.CreateTextRun("A"); element.SetPosAdjustment(140); writer.WriteElement(element); element = eb.CreateTextRun("Y again"); element.SetPosAdjustment(115); writer.WriteElement(element); // Draw the same strings using direct content output... writer.Flush(); // flush pending Element writing operations. // You can also write page content directly to the content stream using // ElementWriter.WriteString(...) and ElementWriter.WriteBuffer(...) methods. // Note that if you are planning to use these functions you need to be familiar // with PDF page content operators (see Appendix A in PDF Reference Manual). // Because it is easy to make mistakes during direct output we recommend that // you use ElementBuilder and Element interface instead. writer.WriteString("T* T* "); // New Lines // writer.WriteElement(eb.CreateTextNewLine()); writer.WriteString("(Direct output to PDF page content stream:) Tj T* "); writer.WriteString("(AWAY) Tj T* "); writer.WriteString("[(A)140(W)140(A)115(Y again)] TJ "); // Finish the block of text writer.WriteElement(eb.CreateTextEnd()); writer.End(); // save changes to the current page doc.PagePushBack(page); // Start a new page ------------------------------------ // Image Masks // // In the opaque imaging model, images mark all areas they occupy on the page as // if with opaque paint. All portions of the image, whether black, white, gray, // or color, completely obscure any marks that may previously have existed in the // same place on the page. // In the graphic arts industry and page layout applications, however, it is common // to crop or 'mask out' the background of an image and then place the masked image // on a different background, allowing the existing background to show through the // masked areas. This sample illustrates how to use image masks. page = doc.PageCreate(); writer.Begin(page); // begin writing to the page // Create the Image Mask MappedFile imgf = new MappedFile(input_path + "imagemask.dat"); FilterReader mask_read = new FilterReader(imgf); ColorSpace device_gray = ColorSpace.CreateDeviceGray(); Image mask = Image.Create(doc, mask_read, 64, 64, 1, device_gray, Image.InputFilter.e_ascii_hex); mask.GetSDFObj().PutBool("ImageMask", true); element = eb.CreateRect(0, 0, 612, 794); element.SetPathStroke(false); element.SetPathFill(true); element.GetGState().SetFillColorSpace(device_gray); element.GetGState().SetFillColor(new ColorPt(0.8)); writer.WritePlacedElement(element); element = eb.CreateImage(mask, new Matrix2D(200, 0, 0, -200, 40, 680)); element.GetGState().SetFillColor(new ColorPt(0.1)); writer.WritePlacedElement(element); element.GetGState().SetFillColorSpace(ColorSpace.CreateDeviceRGB()); element.GetGState().SetFillColor(new ColorPt(1, 0, 0)); element = eb.CreateImage(mask, new Matrix2D(200, 0, 0, -200, 320, 680)); writer.WritePlacedElement(element); element.GetGState().SetFillColor(new ColorPt(0, 1, 0)); element = eb.CreateImage(mask, new Matrix2D(200, 0, 0, -200, 40, 380)); writer.WritePlacedElement(element); { // This sample illustrates Explicit Masking. img = Image.Create(doc, input_path + "peppers.jpg"); // mask is the explicit mask for the primary (base) image img.SetMask(mask); element = eb.CreateImage(img, new Matrix2D(200, 0, 0, -200, 320, 380)); writer.WritePlacedElement(element); } writer.End(); // save changes to the current page doc.PagePushBack(page); // Transparency sample ---------------------------------- // Start a new page ------------------------------------- page = doc.PageCreate(); writer.Begin(page); // begin writing to this page eb.Reset(); // Reset the GState to default // Write some transparent text at the bottom of the page. element = eb.CreateTextBegin(Font.Create(doc, Font.StandardType1Font.e_times_roman), 100); // Set the text knockout attribute. Text knockout must be set outside of // the text group. gstate = element.GetGState(); gstate.SetTextKnockout(false); gstate.SetBlendMode(GState.BlendMode.e_bl_difference); writer.WriteElement(element); element = eb.CreateTextRun("Transparency"); element.SetTextMatrix(1, 0, 0, 1, 30, 30); gstate = element.GetGState(); gstate.SetFillColorSpace(ColorSpace.CreateDeviceCMYK()); gstate.SetFillColor(new ColorPt(1, 0, 0, 0)); gstate.SetFillOpacity(0.5); writer.WriteElement(element); // Write the same text on top the old; shifted by 3 points element.SetTextMatrix(1, 0, 0, 1, 33, 33); gstate.SetFillColor(new ColorPt(0, 1, 0, 0)); gstate.SetFillOpacity(0.5); writer.WriteElement(element); writer.WriteElement(eb.CreateTextEnd()); // Draw three overlapping transparent circles. eb.PathBegin(); // start constructing the path eb.MoveTo(459.223, 505.646); eb.CurveTo(459.223, 415.841, 389.85, 343.04, 304.273, 343.04); eb.CurveTo(218.697, 343.04, 149.324, 415.841, 149.324, 505.646); eb.CurveTo(149.324, 595.45, 218.697, 668.25, 304.273, 668.25); eb.CurveTo(389.85, 668.25, 459.223, 595.45, 459.223, 505.646); element = eb.PathEnd(); element.SetPathFill(true); gstate = element.GetGState(); gstate.SetFillColorSpace(ColorSpace.CreateDeviceRGB()); gstate.SetFillColor(new ColorPt(0, 0, 1)); // Blue Circle gstate.SetBlendMode(GState.BlendMode.e_bl_normal); gstate.SetFillOpacity(0.5); writer.WriteElement(element); // Translate relative to the Blue Circle gstate.SetTransform(1, 0, 0, 1, 113, -185); gstate.SetFillColor(new ColorPt(0, 1, 0)); // Green Circle gstate.SetFillOpacity(0.5); writer.WriteElement(element); // Translate relative to the Green Circle gstate.SetTransform(1, 0, 0, 1, -220, 0); gstate.SetFillColor(new ColorPt(1, 0, 0)); // Red Circle gstate.SetFillOpacity(0.5); writer.WriteElement(element); writer.End(); // save changes to the current page doc.PagePushBack(page); // End page ------------------------------------ } doc.Save(output_path + "element_builder.pdf", SDFDoc.SaveOptions.e_remove_unused); Console.WriteLine("Done. Result saved in element_builder.pdf..."); } } catch (PDFNetException e) { Console.WriteLine(e.Message); } }
/// <summary> //----------------------------------------------------------------------------------- // This sample illustrates how to embed various raster image formats // (e.g. TIFF, JPEG, JPEG2000, JBIG2, GIF, PNG, BMP, etc.) in a PDF document. //----------------------------------------------------------------------------------- /// </summary> static void Main(string[] args) { PDFNet.Initialize(); // Relative path to the folder containing test files. string input_path = "../../TestFiles/"; string output_path = "../../TestFiles/Output/"; try { using (PDFDoc doc = new PDFDoc()) using (ElementBuilder bld = new ElementBuilder()) // Used to build new Element objects using (ElementWriter writer = new ElementWriter()) // Used to write Elements to the page { Page page = doc.PageCreate(); // Start a new page writer.Begin(page); // Begin writing to this page // ---------------------------------------------------------- // Embed a JPEG image to the output document. Image img = Image.Create(doc, input_path + "peppers.jpg"); // You can also directly add any .NET Bitmap. The following commented-out code // is equivalent to the above line: // System.Drawing.Bitmap bmp; // System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(input_path + "peppers.jpg"); // Image img = Image.Create(doc, bmp); Element element = bld.CreateImage(img, 50, 500, img.GetImageWidth() / 2, img.GetImageHeight() / 2); writer.WritePlacedElement(element); // ---------------------------------------------------------- // Add a PNG image to the output file img = Image.Create(doc, input_path + "butterfly.png"); element = bld.CreateImage(img, new Matrix2D(100, 0, 0, 100, 300, 500)); writer.WritePlacedElement(element); // ---------------------------------------------------------- // Add a GIF image to the output file img = Image.Create(doc, input_path + "pdfnet.gif"); element = bld.CreateImage(img, new Matrix2D(img.GetImageWidth(), 0, 0, img.GetImageHeight(), 50, 350)); writer.WritePlacedElement(element); // ---------------------------------------------------------- // Add a TIFF image to the output file img = Image.Create(doc, input_path + "grayscale.tif"); element = bld.CreateImage(img, new Matrix2D(img.GetImageWidth(), 0, 0, img.GetImageHeight(), 10, 50)); writer.WritePlacedElement(element); writer.End(); // Save the page doc.PagePushBack(page); // Add the page to the document page sequence // ---------------------------------------------------------- // Add a BMP image to the output file /* * bmp = new System.Drawing.Bitmap(input_path + "pdftron.bmp"); * img = Image.Create(doc, bmp); * element = bld.CreateImage(img, new Matrix2D(bmp.Width, 0, 0, bmp.Height, 255, 700)); * writer.WritePlacedElement(element); * * writer.End(); // Finish writing to the page * doc.PagePushBack(page); */ // ---------------------------------------------------------- // Embed a monochrome TIFF. Compress the image using lossy JBIG2 filter. page = doc.PageCreate(new pdftron.PDF.Rect(0, 0, 612, 794)); writer.Begin(page); // begin writing to this page // Note: encoder hints can be used to select between different compression methods. // For example to instruct PDFNet to compress a monochrome image using JBIG2 compression. ObjSet hint_set = new ObjSet(); Obj enc = hint_set.CreateArray(); // Initialize encoder 'hint' parameter enc.PushBackName("JBIG2"); enc.PushBackName("Lossy"); img = pdftron.PDF.Image.Create(doc, input_path + "multipage.tif", enc); element = bld.CreateImage(img, new Matrix2D(612, 0, 0, 794, 0, 0)); writer.WritePlacedElement(element); writer.End(); // Save the page doc.PagePushBack(page); // Add the page to the document page sequence // ---------------------------------------------------------- // Add a JPEG2000 (JP2) image to the output file // Create a new page page = doc.PageCreate(); writer.Begin(page); // Begin writing to the page // Embed the image. img = pdftron.PDF.Image.Create(doc, input_path + "palm.jp2"); // Position the image on the page. element = bld.CreateImage(img, new Matrix2D(img.GetImageWidth(), 0, 0, img.GetImageHeight(), 96, 80)); writer.WritePlacedElement(element); // Write 'JPEG2000 Sample' text string under the image. writer.WriteElement(bld.CreateTextBegin(pdftron.PDF.Font.Create(doc, pdftron.PDF.Font.StandardType1Font.e_times_roman), 32)); element = bld.CreateTextRun("JPEG2000 Sample"); element.SetTextMatrix(1, 0, 0, 1, 190, 30); writer.WriteElement(element); writer.WriteElement(bld.CreateTextEnd()); writer.End(); // Finish writing to the page doc.PagePushBack(page); doc.Save(output_path + "addimage.pdf", SDFDoc.SaveOptions.e_linearized); Console.WriteLine("Done. Result saved in addimage.pdf..."); } } catch (PDFNetException e) { Console.WriteLine(e.Message); } }