static void Main(string[] args) { PDFNet.Initialize(); // Relative path to the folder containing test files. string input_path = "../../TestFiles/"; try { Console.WriteLine("-------------------------------------------------"); Console.WriteLine("Sample 1 - Extract text data from all pages in the document."); // Open the test file Console.WriteLine("Opening the input pdf..."); using (PDFDoc doc = new PDFDoc(input_path + "newsletter.pdf")) using (ElementReader page_reader = new ElementReader()) { doc.InitSecurityHandler(); PageIterator itr; for (itr = doc.GetPageIterator(); itr.HasNext(); itr.Next()) // Read every page { page_reader.Begin(itr.Current()); ProcessElements(page_reader); page_reader.End(); } 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/"; Console.WriteLine("_______________________________________________"); Console.WriteLine("Opening the input pdf..."); try // Test - Adjust the position of content within the page. { using (PDFDoc input_doc = new PDFDoc(input_path + "tiger.pdf")) { input_doc.InitSecurityHandler(); Page pg = input_doc.GetPage(1); Rect media_box = pg.GetMediaBox(); media_box.x1 -= 200; // translate the page 200 units (1 uint = 1/72 inch) media_box.x2 -= 200; media_box.Update(); input_doc.Save(output_path + "tiger_shift.pdf", 0); } Console.WriteLine("Done. Result saved in tiger_shift..."); } catch (PDFNetException e) { Console.WriteLine(e.Message); } }
public void RunPdfTron(string input_path) { PDFNet.Initialize(); // string output_path = "../../../../TestFiles/Output/"; try { // Open the test file PDFDoc doc = new PDFDoc(input_path); doc.InitSecurityHandler(); PageIterator itr; ElementReader page_reader = new ElementReader(); for (itr = doc.GetPageIterator(); itr.HasNext(); itr.Next()) // Read every page { int pageno = itr.GetPageNumber(); page_reader.Begin(itr.Current()); ProcessElements(page_reader); page_reader.End(); } page_reader.Dispose(); // Calling Dispose() on ElementReader/Writer/Builder can result in increased performance and lower memory consumption. doc.Close(); } catch (PDFNetException e) { ConsoleLog += e.Message; } PDFNet.Terminate(); }
static void Main(string[] args) { PDFNet.Initialize(); try { using (PDFDoc doc = new PDFDoc(input_path + "numbered.pdf")) { doc.InitSecurityHandler(); // An example of using SDF/Cos API to add any type of annotations. AnnotationLowLevelAPI(doc); doc.Save(output_path + "annotation_test1.pdf", SDFDoc.SaveOptions.e_linearized); System.Console.WriteLine("Done. Results saved in annotation_test1.pdf"); // An example of using the high-level PDFNet API to read existing annotations, // to edit existing annotations, and to create new annotation from scratch. AnnotationHighLevelAPI(doc); doc.Save(output_path + "annotation_test2.pdf", SDFDoc.SaveOptions.e_linearized); System.Console.WriteLine("Done. Results saved in annotation_test2.pdf"); } // an example of creating various annotations in a brand new document using (PDFDoc doc1 = new PDFDoc()) { CreateTestAnnots(doc1); doc1.Save(output_path + "new_annot_test_api.pdf", SDFDoc.SaveOptions.e_linearized); System.Console.WriteLine("Saved new_annot_test_api.pdf"); } } catch (PDFNetException e) { System.Console.WriteLine(e.Message); } }
/// <summary> /// The following sample illustrates how to redact a PDF document using 'pdftron.PDF.Redactor'. /// </summary> static void Main(string[] args) { PDFNet.Initialize(); string input_path = "../../TestFiles/"; string output_path = "../../TestFiles/Output/"; try { ArrayList rarr = new ArrayList(); rarr.Add(new Redactor.Redaction(1, new Rect(100, 100, 550, 600), false, "Top Secret")); rarr.Add(new Redactor.Redaction(2, new Rect(30, 30, 450, 450), true, "Negative Redaction")); rarr.Add(new Redactor.Redaction(2, new Rect(0, 0, 100, 100), false, "Positive")); rarr.Add(new Redactor.Redaction(2, new Rect(100, 100, 200, 200), false, "Positive")); rarr.Add(new Redactor.Redaction(2, new Rect(300, 300, 400, 400), false, "")); rarr.Add(new Redactor.Redaction(2, new Rect(500, 500, 600, 600), false, "")); rarr.Add(new Redactor.Redaction(3, new Rect(0, 0, 700, 20), false, "")); Redactor.Appearance app = new Redactor.Appearance(); app.RedactionOverlay = true; app.Border = false; app.ShowRedactedContentRegions = true; Redact(input_path + "newsletter.pdf", output_path + "redacted.pdf", rarr, app); Console.WriteLine("Done..."); } catch (PDFNetException e) { Console.WriteLine(e.Message); } }
/// <summary> /// The main entry point for the application. /// </summary> static void Main(string[] args) { // The first step in every application using PDFNet is to initialize the // library and set the path to common PDF resources. The library is usually // initialized only once, but calling Initialize() multiple times is also fine. PDFNet.Initialize(); PDFNet.AddResourceSearchPath("../../../../../Lib/"); if (!CADModule.IsModuleAvailable()) { Console.WriteLine(); Console.WriteLine("Unable to run CAD2PDFTest: PDFTron SDK CAD module not available."); Console.WriteLine("---------------------------------------------------------------"); Console.WriteLine("The CAD module is an optional add-on, available for download"); Console.WriteLine("at http://www.pdftron.com/. If you have already downloaded this"); Console.WriteLine("module, ensure that the SDK is able to find the required files"); Console.WriteLine("using the PDFNet::AddResourceSearchPath() function."); Console.WriteLine(); } // Relative path to the folder containing test files. string input_path = "../../TestFiles/CAD/"; string output_path = "../../TestFiles/Output/"; string input_file_name = "construction drawings color-28.05.18.dwg"; string output_file_name = "construction drawings color-28.05.18.pdf"; if (args.Length != 0) { input_file_name = args[0]; output_file_name = input_file_name + ".pdf"; } Console.WriteLine("Example cad:"); try { using (PDFDoc pdfdoc = new PDFDoc()) { if (IsRVTFile(input_file_name)) { CADConvertOptions opts = new CADConvertOptions(); opts.SetPageWidth(800); opts.SetPageHeight(600); opts.SetRasterDPI(150); pdftron.PDF.Convert.FromCAD(pdfdoc, input_path + input_file_name, opts); } else { pdftron.PDF.Convert.FromCAD(pdfdoc, input_path + input_file_name, null); } pdfdoc.Save(output_path + output_file_name, SDFDoc.SaveOptions.e_remove_unused); } Console.WriteLine("Done."); } catch (PDFNetException e) { Console.WriteLine(e.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); } }
static void Main(string[] args) { PDFNet.Initialize(); // Create a PDF Package. try { using (PDFDoc doc = new PDFDoc()) { AddPackage(doc, input_path + "numbered.pdf", "My File 1"); AddPackage(doc, input_path + "newsletter.pdf", "My Newsletter..."); AddPackage(doc, input_path + "peppers.jpg", "An image"); AddCovePage(doc); doc.Save(output_path + "package.pdf", SDFDoc.SaveOptions.e_linearized); Console.WriteLine("Done."); } } catch (PDFNetException e) { Console.WriteLine(e.Message); } // Extract parts from a PDF Package. try { using (PDFDoc doc = new PDFDoc(output_path + "package.pdf")) { doc.InitSecurityHandler(); pdftron.SDF.NameTree files = NameTree.Find(doc, "EmbeddedFiles"); if (files.IsValid()) { // Traverse the list of embedded files. NameTreeIterator i = files.GetIterator(); for (int counter = 0; i.HasNext(); i.Next(), ++counter) { string entry_name = i.Key().GetAsPDFText(); Console.WriteLine("Part: {0}", entry_name); FileSpec file_spec = new FileSpec(i.Value()); Filter stm = file_spec.GetFileData(); if (stm != null) { string fname = output_path + "extract_" + counter.ToString() + ".pdf"; stm.WriteToFile(fname, false); } } } } Console.WriteLine("Done."); } catch (PDFNetException e) { Console.WriteLine(e.Message); } }
public PdfTronForm() { InitializeComponent(); PDFNetLoader loader = PDFNetLoader.Instance(); PDFNet.SetTempPath("C:\\ProgramData\\ActivePDF\\DocConverter\\Watch Folders\\Default\\Temp"); PDFNet.Initialize(); HTML2PDF.SetModulePath(Environment.CurrentDirectory + "\\html2pdf.dll"); }
public PdfView() { this.InitializeComponent(); this.navigationHelper = new NavigationHelper(this); PDFNet.Initialize(); pdfViewCtrl = new PDFViewCtrl(); PDFViewBorder.Child = pdfViewCtrl; MyToolManager = new ToolManager(pdfViewCtrl); }
static void Main(string[] args) { PDFNet.Initialize(); // Relative path to the folder containing test files. string input_path = "../../TestFiles/"; string output_path = "../../TestFiles/Output/"; string input_filename = "newsletter.pdf"; string output_filename = "newsletter_edited.pdf"; try { Console.WriteLine("Opening the input file..."); using (PDFDoc doc = new PDFDoc(input_path + input_filename)) { doc.InitSecurityHandler(); ElementWriter writer = new ElementWriter(); ElementReader reader = new ElementReader(); XSet visited = new XSet(); PageIterator itr = doc.GetPageIterator(); while (itr.HasNext()) { try { Page page = itr.Current(); visited.Add(page.GetSDFObj().GetObjNum()); reader.Begin(page); writer.Begin(page, ElementWriter.WriteMode.e_replacement, false, true, page.GetResourceDict()); ProcessElements(reader, writer, visited); writer.End(); reader.End(); itr.Next(); } catch (PDFNetException e) { Console.WriteLine(e.Message); } } doc.Save(output_path + output_filename, SDFDoc.SaveOptions.e_remove_unused); Console.WriteLine("Done. Result saved in {0}...", output_filename); } } catch (PDFNetException e) { Console.WriteLine(e.Message); } }
// // This method is invoked when the application has loaded and is ready to run. In this // method you should instantiate the window, load the UI into it and then make the window // visible. // // You have 17 seconds to return from this method, or iOS will terminate your application. // public override bool FinishedLaunching(UIApplication app, NSDictionary options) { global::Xamarin.Forms.Forms.Init(); CopyResToFiles(); PDFNet.Initialize("LICENSE_KEY"); Locator.CurrentMutable.RegisterConstant <ITextExtractor>(new PdfTronTextExtractor()); LoadApplication(new App()); return(base.FinishedLaunching(app, options)); }
public static Pdf Convert(string path, bool savePdfStructureAsXml = false, string xmlName = "pdf.xml") { PDFNet.Initialize(); using (var doc = new PDFDoc(path)) { var result = new XDocument(new XElement("Pdf")); for (int i = 1; i <= doc.GetPageCount(); i++) { var page = doc.GetPage(i); using (var txt = new TextExtractor()) { txt.Begin(page); var text = txt.GetAsXML(TextExtractor.XMLOutputFlags.e_words_as_elements | TextExtractor.XMLOutputFlags.e_output_bbox); //combine words within a line (we don't need their position) var xml = XDocument.Load(new MemoryStream(Encoding.UTF8.GetBytes(text))); var lines = xml.Root.DescendantsAndSelf().Where(s => s.Name == "Line").ToArray(); foreach (var line in lines) { var t = String.Join(" ", line.DescendantsAndSelf("Word").Select(s => s.Value)); line.RemoveNodes(); line.SetValue(t); } result.Root.Add(xml.Root); } } //save the temporary xml just for debug purposes if (savePdfStructureAsXml) { var destinationPath = Path.GetDirectoryName(path) + xmlName; using (var writer = new XmlTextWriter(destinationPath, null)) { writer.Formatting = Formatting.Indented; result.Save(writer); } } using (var ms = new MemoryStream()) { result.Save(ms); ms.Seek(0, SeekOrigin.Begin); var serializer = new XmlSerializer(typeof(Pdf)); return((Pdf)serializer.Deserialize(ms)); } } }
protected override void OnCreate(Bundle savedInstanceState) { TabLayoutResource = Resource.Layout.Tabbar; ToolbarResource = Resource.Layout.Toolbar; base.OnCreate(savedInstanceState); global::Xamarin.Forms.Forms.Init(this, savedInstanceState); CopyResToFiles(); PDFNet.Initialize(this, Resource.Raw.pdfnet, "LICENSE_KEY"); Locator.CurrentMutable.RegisterConstant <ITextExtractor>(new PdfTronTextExtractor()); LoadApplication(new App()); }
static void Main(string[] args) { PDFNet.Initialize(); PDFNet.SetColorManagement(PDFNet.CMSType.e_lcms); // Required for PDFA validation. //----------------------------------------------------------- // Example 1: PDF/A Validation //----------------------------------------------------------- try { string filename = "newsletter.pdf"; using (PDFACompliance pdf_a = new PDFACompliance(false, input_path + filename, null, PDFACompliance.Conformance.e_Level1B, null, 10, false)) { PrintResults(pdf_a, filename); } } catch (pdftron.Common.PDFNetException e) { Console.WriteLine(e.Message); } //----------------------------------------------------------- // Example 2: PDF/A Conversion //----------------------------------------------------------- try { string filename = "fish.pdf"; using (PDFACompliance pdf_a = new PDFACompliance(true, input_path + filename, null, PDFACompliance.Conformance.e_Level1B, null, 10, false)) { filename = "pdfa.pdf"; pdf_a.SaveAs(output_path + filename, true); } // Re-validate the document after the conversion... filename = "pdfa.pdf"; using (PDFACompliance pdf_a = new PDFACompliance(false, output_path + filename, null, PDFACompliance.Conformance.e_Level1B, null, 10, false)) { PrintResults(pdf_a, filename); } } catch (pdftron.Common.PDFNetException e) { Console.WriteLine(e.Message); } Console.WriteLine("PDFACompliance test completed."); }
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) { try { PDFNet.Initialize(); Console.WriteLine("-------------------------------------------------"); Console.WriteLine("Extract page element information from all "); Console.WriteLine("pages in the document."); // Open the test file using (PDFDoc doc = new PDFDoc(input_path + "newsletter.pdf")) { doc.InitSecurityHandler(); int pgnum = doc.GetPageCount(); PageIterator itr; using (ElementReader page_reader = new ElementReader()) { for (itr = doc.GetPageIterator(); itr.HasNext(); itr.Next()) // Read every page { Console.WriteLine("Page {0:d}----------------------------------------", itr.GetPageNumber()); Rect crop_box = itr.Current().GetCropBox(); crop_box.Normalize(); // Console.WriteLine(" Page Rectangle: x={0:f} y={1:f} x2={2:f} y2={3:f}", crop_box.x1, crop_box.y1, crop_box.x2, crop_box.y2); // Console.WriteLine(" Page Size: width={0:f} height={1:f}", crop_box.Width(), crop_box.Height()); page_reader.Begin(itr.Current()); ProcessElements(page_reader); page_reader.End(); } } Console.WriteLine("Done."); } } catch (PDFNetException e) { Console.WriteLine(e.Message); } }
static void Main(string[] args) { PDFNet.Initialize(); // Sample 1: // Directly convert from PDF to XOD. pdftron.PDF.Convert.ToXod(inputPath + "newsletter.pdf", outputPath + "from_pdf.xod"); // Sample 2: // Directly convert from generic XPS to XOD. pdftron.PDF.Convert.ToXod(inputPath + "simple-xps.xps", outputPath + "from_xps.xod"); // Sample 3: // Convert from MS Office (does not require printer driver for Office 2007+) // and other document formats to XOD. BulkConvertRandomFilesToXod(); Console.WriteLine("Done."); }
public MainViewModel() { // Initilizes PDFNet PDFNet.Initialize(); // Make sure to Terminate any processes Application.Current.SessionEnding += Current_SessionEnding; // Init all Commands CMDOpenDocument = new Relaycommand(OpenDocument); CMDNextPage = new Relaycommand(NextPage); CMDPreviousPage = new Relaycommand(PreviousPage); CMDAnottateText = new Relaycommand(AddTextSample); CMDFreeTextSample = new Relaycommand(AddFreeTextSample); CMDSelectText = new Relaycommand(SelectText); CMDExit = new Relaycommand(ExitApp); CMDZoomIn = new Relaycommand(ZoomIn); CMDZoomOut = new Relaycommand(ZoomOut); CMDUndo = new Relaycommand(Undo); CMDRedo = new Relaycommand(Redo); // Checks the scale factor to determine the right resolution PresentationSource source = PresentationSource.FromVisual(Application.Current.MainWindow); double scaleFactor = 1; if (source != null) { scaleFactor = 1 / source.CompositionTarget.TransformFromDevice.M11; } // Set working doc to Viewer PDFViewer = new PDFViewWPF(); PDFViewer.PixelsPerUnitWidth = scaleFactor; // PDF Viewer Events subscription PDFViewer.MouseLeftButtonDown += PDFView_MouseLeftButtonDown; // Enable access to the Tools available _toolManager = new ToolManager(PDFViewer); _toolManager.AnnotationAdded += _toolManager_AnnotationAdded; _toolManager.AnnotationRemoved += _toolManager_AnnotationRemoved; }
public string Test() { string s = ""; // 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 { string input_path = "./TestFiles/"; s = processOCR(input_path + "discharge-summary.pdf"); return(s); } catch (PDFNetException e) { return(e.Message); } }
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); } }
static void Main(string[] args) { PDFNet.Initialize(); Boolean err = false; err = ConvertToPdfFromFile(); if (err) { Console.WriteLine("ConvertFile failed"); } else { Console.WriteLine("ConvertFile succeeded"); } err = ConvertSpecificFormats(); if (err) { Console.WriteLine("ConvertSpecificFormats failed"); } else { Console.WriteLine("ConvertSpecificFormats succeeded"); } err = ConvertToXpsFromFile(); if (err) { Console.WriteLine("ConvertToXpsFromFile failed"); } else { Console.WriteLine("ConvertToXpsFromFile succeeded"); } Console.WriteLine("Done."); }
/// <summary> /// The main entry point for the application. /// </summary> static void Main(string[] args) { PDFNet.Initialize(); try { // first the one-line conversion method SimpleConvert("simple-word_2007.docx", "simple-word_2007.pdf"); // then the more flexible line-by-line conversion API FlexibleConvert("the_rime_of_the_ancient_mariner.docx", "the_rime_of_the_ancient_mariner.pdf"); } catch (pdftron.Common.PDFNetException e) { Console.WriteLine(e.Message); } catch (Exception e) { Console.WriteLine("Unrecognized Exception: " + e.Message); } PDFNet.Terminate(); Console.WriteLine("Done."); }
/// <summary> /// The main entry point for the application. /// </summary> static void Main(string[] args) { // The first step in every application using PDFNet is to initialize the // library and set the path to common PDF resources. The library is usually // initialized only once, but calling Initialize() multiple times is also fine. PDFNet.Initialize(); try { // Optional: Set ICC color profiles to fine tune color conversion // for PDF 'device' color spaces. You can use your own ICC profiles. // Standard Adobe color profiles can be download from Adobes site: // http://www.adobe.com/support/downloads/iccprofiles/iccprofiles_win.html // // Simply drop all *.icc files in PDFNet resource folder or you specify // the full pathname. //--- // PDFNet.SetResourcesPath("../../../../../resources"); // PDFNet.SetColorManagement(); // PDFNet.SetDefaultDeviceCMYKProfile("USWebCoatedSWOP.icc"); // will search in PDFNet resource folder. // PDFNet.SetDefaultDeviceRGBProfile("AdobeRGB1998.icc"); // Optional: Set predefined font mappings to override default font // substitution for documents with missing fonts. For example: //--- // PDFNet.AddFontSubst("StoneSans-Semibold", "C:/WINDOWS/Fonts/comic.ttf"); // PDFNet.AddFontSubst("StoneSans", "comic.ttf"); // search for 'comic.ttf' in PDFNet resource folder. // PDFNet.AddFontSubst(PDFNet.CharacterOrdering.e_Identity, "C:/WINDOWS/Fonts/arialuni.ttf"); // PDFNet.AddFontSubst(PDFNet.CharacterOrdering.e_Japan1, "C:/Program Files/Adobe/Acrobat 7.0/Resource/CIDFont/KozMinProVI-Regular.otf"); // PDFNet.AddFontSubst(PDFNet.CharacterOrdering.e_Japan2, "c:/myfonts/KozMinProVI-Regular.otf"); // // If fonts are in PDFNet resource folder, it is not necessary to specify // the full path name. For example, //--- // PDFNet.AddFontSubst(PDFNet.CharacterOrdering.e_Korea1, "AdobeMyungjoStd-Medium.otf"); // PDFNet.AddFontSubst(PDFNet.CharacterOrdering.e_CNS1, "AdobeSongStd-Light.otf"); // PDFNet.AddFontSubst(PDFNet.CharacterOrdering.e_GB1, "AdobeMingStd-Light.otf"); } catch (Exception) { Console.WriteLine("The specified color profile was not found."); } // Relative path to the folder containing test files. string input_path = "../../TestFiles/"; string output_path = "../../TestFiles/Output/"; using (PDFDraw draw = new PDFDraw()) { //-------------------------------------------------------------------------------- // Example 1) Convert the first PDF page to PNG at 92 DPI. // A three step tutorial to convert PDF page to an image. try { // A) Open the PDF document. using (PDFDoc doc = new PDFDoc(input_path + "tiger.pdf")) { // Initialize the security handler, in case the PDF is encrypted. doc.InitSecurityHandler(); // B) The output resolution is set to 92 DPI. draw.SetDPI(92); // C) Rasterize the first page in the document and save the result as PNG. Page pg = doc.GetPage(1); draw.Export(pg, output_path + "tiger_92dpi.png"); Console.WriteLine("Example 1: tiger_92dpi.png"); // Export the same page as TIFF draw.Export(pg, output_path + "tiger_92dpi.tif", "TIFF"); } } catch (PDFNetException e) { Console.WriteLine(e.Message); } //-------------------------------------------------------------------------------- // Example 2) Convert the all pages in a given document to JPEG at 72 DPI. ObjSet hint_set = new ObjSet(); // A collection of rendering 'hits'. Console.WriteLine("Example 2:"); try { using (PDFDoc doc = new PDFDoc(input_path + "newsletter.pdf")) { // Initialize the security handler, in case the PDF is encrypted. doc.InitSecurityHandler(); draw.SetDPI(72); // Set the output resolution is to 72 DPI. // Use optional encoder parameter to specify JPEG quality. Obj encoder_param = hint_set.CreateDict(); encoder_param.PutNumber("Quality", 80); // Traverse all pages in the document. for (PageIterator itr = doc.GetPageIterator(); itr.HasNext(); itr.Next()) { string output_filename = string.Format("newsletter{0:d}.jpg", itr.GetPageNumber()); Console.WriteLine("newsletter{0:d}.jpg", itr.GetPageNumber()); draw.Export(itr.Current(), output_path + output_filename, "JPEG", encoder_param); } } Console.WriteLine("Done."); } catch (PDFNetException e) { Console.WriteLine(e.Message); } try // Examples 3-6 { // Common code for remaining samples. using (PDFDoc tiger_doc = new PDFDoc(input_path + "tiger.pdf")) { // Initialize the security handler, in case the PDF is encrypted. tiger_doc.InitSecurityHandler(); Page page = tiger_doc.GetPage(1); //-------------------------------------------------------------------------------- // Example 3) Convert the first page to GDI+ Bitmap. Also, rotate the // page 90 degrees and save the result as RAW. draw.SetDPI(100); // Set the output resolution is to 100 DPI. draw.SetRotate(Page.Rotate.e_90); // Rotate all pages 90 degrees clockwise. BitmapInfo buf = draw.GetBitmap(page, PDFDraw.PixelFormat.e_rgb, false); // Save the raw RGB data to disk. string filename = "tiger_100dpi_rot90.raw"; System.IO.File.WriteAllBytes(output_path + filename, buf.Buffer); Console.WriteLine("Example 3: tiger_100dpi_rot90.raw"); draw.SetRotate(Page.Rotate.e_0); // Disable image rotation for remaining samples. //-------------------------------------------------------------------------------- // Example 4) Convert PDF page to a fixed image size. Also illustrates some // other features in PDFDraw class such as rotation, image stretching, exporting // to grayscale, or monochrome. // Initialize render 'gray_hint' parameter, that is used to control the // rendering process. In this case we tell the rasterizer to export the image as // 1 Bit Per Component (BPC) image. Obj mono_hint = hint_set.CreateDict(); mono_hint.PutNumber("BPC", 1); // SetImageSize can be used instead of SetDPI() to adjust page scaling // dynamically so that given image fits into a buffer of given dimensions. draw.SetImageSize(1000, 1000); // Set the output image to be 1000 wide and 1000 pixels tall draw.Export(page, output_path + "tiger_1000x1000.png", "PNG", mono_hint); Console.WriteLine("Example 4: tiger_1000x1000.png"); draw.SetImageSize(200, 400); // Set the output image to be 200 wide and 300 pixels tall draw.SetRotate(Page.Rotate.e_180); // Rotate all pages 90 degrees clockwise. // 'gray_hint' tells the rasterizer to export the image as grayscale. Obj gray_hint = hint_set.CreateDict(); gray_hint.PutName("ColorSpace", "Gray"); draw.Export(page, output_path + "tiger_200x400_rot180.png", "PNG", gray_hint); Console.WriteLine("Example 4: tiger_200x400_rot180.png"); draw.SetImageSize(400, 200, false); // The third parameter sets 'preserve-aspect-ratio' to false. draw.SetRotate(Page.Rotate.e_0); // Disable image rotation. draw.Export(page, output_path + "tiger_400x200_stretch.jpg", "JPEG"); Console.WriteLine("Example 4: tiger_400x200_stretch.jpg"); //-------------------------------------------------------------------------------- // Example 5) Zoom into a specific region of the page and rasterize the // area at 200 DPI and as a thumbnail (i.e. a 50x50 pixel image). page.SetCropBox(new Rect(216, 522, 330, 600)); // Set the page crop box. // Select the crop region to be used for drawing. draw.SetPageBox(Page.Box.e_crop); draw.SetDPI(900); // Set the output image resolution to 900 DPI. draw.Export(page, output_path + "tiger_zoom_900dpi.png", "PNG"); Console.WriteLine("Example 5: tiger_zoom_900dpi.png"); // ------------------------------------------------------------------------------- // Example 6) draw.SetImageSize(50, 50); // Set the thumbnail to be 50x50 pixel image. draw.Export(page, output_path + "tiger_zoom_50x50.png", "PNG"); Console.WriteLine("Example 6: tiger_zoom_50x50.png"); } } catch (PDFNetException e) { Console.WriteLine(e.Message); } Obj cmyk_hint = hint_set.CreateDict(); cmyk_hint.PutName("ColorSpace", "CMYK"); //-------------------------------------------------------------------------------- // Example 7) Convert the first PDF page to CMYK TIFF at 92 DPI. // A three step tutorial to convert PDF page to an image. try { // A) Open the PDF document. using (PDFDoc doc = new PDFDoc(input_path + "tiger.pdf")) { // Initialize the security handler, in case the PDF is encrypted. doc.InitSecurityHandler(); // B) The output resolution is set to 92 DPI. draw.SetDPI(92); // C) Rasterize the first page in the document and save the result as TIFF. Page pg = doc.GetPage(1); draw.Export(pg, output_path + "out1.tif", "TIFF", cmyk_hint); Console.WriteLine("Example 7: out1.tif"); } } catch (PDFNetException e) { Console.WriteLine(e.Message); } //-------------------------------------------------------------------------------- // Example 8) Export raster content to PNG using different image smoothing settings. try { // A) Open the PDF document. using (PDFDoc doc = new PDFDoc(input_path + "tiger.pdf")) { // Initialize the security handler, in case the PDF is encrypted. doc.InitSecurityHandler(); // B) Get the page matrix Page pg = doc.GetPage(1); Page.Box box = Page.Box.e_crop; Matrix2D mtx = pg.GetDefaultMatrix(true, box); // We want to render a quadrant, so use half of width and height double pg_w = pg.GetPageWidth(box) / 2; double pg_h = pg.GetPageHeight(box) / 2; // C) Scale matrix from PDF space to buffer space double dpi = 96.0; double scale = dpi / 72.0; // PDF space is 72 dpi int buf_w = (int)(Math.Floor(scale * pg_w)); int buf_h = (int)(Math.Floor(scale * pg_h)); int bytes_per_pixel = 4; // BGRA buffer int buf_size = buf_w * buf_h * bytes_per_pixel; mtx.Translate(0, -pg_h); // translate by '-pg_h' since we want south-west quadrant mtx = new Matrix2D(scale, 0, 0, scale, 0, 0) * mtx; // D) Rasterize page into memory buffer, according to our parameters byte[] buf; PDFRasterizer rast = new PDFRasterizer(); buf = rast.Rasterize(pg, buf_w, buf_h, buf_w * bytes_per_pixel, bytes_per_pixel, true, mtx); // buf now contains raw BGRA bitmap. Console.WriteLine("Example 8: Successfully rasterized into memory buffer."); } } catch (PDFNetException e) { Console.WriteLine(e.Message); } //-------------------------------------------------------------------------------- // Example 9) Export raster content to PNG using different image smoothing settings. try { using (PDFDoc text_doc = new PDFDoc(input_path + "lorem_ipsum.pdf")) { text_doc.InitSecurityHandler(); draw.SetImageSmoothing(false, false); string filename = "raster_text_no_smoothing.png"; draw.Export(text_doc.GetPageIterator().Current(), output_path + filename); Console.WriteLine("Example 9 a): " + filename + ". Done."); filename = "raster_text_smoothed.png"; draw.SetImageSmoothing(true, false /*default quality bilinear resampling*/); draw.Export(text_doc.GetPageIterator().Current(), output_path + filename); Console.WriteLine("Example 9 b): " + filename + ". Done."); filename = "raster_text_high_quality.png"; draw.SetImageSmoothing(true, true /*high quality area resampling*/); draw.Export(text_doc.GetPageIterator().Current(), output_path + filename); Console.WriteLine("Example 9 c): " + filename + ". Done."); } } catch (Exception e) { Console.WriteLine(e.Message); } //-------------------------------------------------------------------------------- // Example 10) Export separations directly, without conversion to an output colorspace try { using (PDFDoc separation_doc = new PDFDoc(input_path + "op_blend_test.pdf")) { separation_doc.InitSecurityHandler(); Obj separation_hint = hint_set.CreateDict(); separation_hint.PutName("ColorSpace", "Separation"); draw.SetDPI(96); draw.SetImageSmoothing(true, true); draw.SetOverprint(PDFRasterizer.OverprintPreviewMode.e_op_on); string filename = "merged_separations.png"; draw.Export(separation_doc.GetPageIterator().Current(), output_path + filename, "PNG"); Console.WriteLine("Example 10 a): " + filename + ". Done."); filename = "separation"; draw.Export(separation_doc.GetPageIterator().Current(), output_path + filename, "PNG", separation_hint); Console.WriteLine("Example 10 b): " + filename + "_[ink].png. Done."); filename = "separation_NChannel.tif"; draw.Export(separation_doc.GetPageIterator().Current(), output_path + filename, "TIFF", separation_hint); Console.WriteLine("Example 10 c): " + filename + ". Done."); } } catch (PDFNetException e) { Console.WriteLine(e.Message); } } // using PDFDraw }
public MainWindow() { InitializeComponent(); PDFNet.Initialize(); }
static OfficeConverter() { PDFNetLoader.Instance(); PDFNet.Initialize(); }
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/"; 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); } }
public void ReadAdvanced(string input_path) { PDFNet.Initialize(); try { PDFDoc doc = new PDFDoc(input_path); doc.InitSecurityHandler(); Page page = doc.GetPage(1); if (page == null) { ConsoleLog += "Page not found."; return; } TextExtractor txt = new TextExtractor(); txt.Begin(page); // Read the page. // Other options you may want to consider... // txt.Begin(page, null, TextExtractor.ProcessingFlags.e_no_dup_remove); // txt.Begin(page, null, TextExtractor.ProcessingFlags.e_remove_hidden_text); // ... // Example 1. Get all text on the page in a single string. // Words will be separated with space or new line characters. if (example1_basic) { // Get the word count. ConsoleLog += "Word Count: {0}" + txt.GetWordCount(); ConsoleLog += "\n\n- GetAsText --------------------------\n{0}" + txt.GetAsText(); ConsoleLog += "-----------------------------------------------------------"; } // Example 2. Get XML logical structure for the page. if (example2_xml) { String text = txt.GetAsXML(TextExtractor.XMLOutputFlags.e_words_as_elements | TextExtractor.XMLOutputFlags.e_output_bbox | TextExtractor.XMLOutputFlags.e_output_style_info); ConsoleLog += "\n\n- GetAsXML --------------------------\n{0}" + text; ConsoleLog += "-----------------------------------------------------------"; } // Example 3. Extract words one by one. if (example3_wordlist) { TextExtractor.Word word; for (TextExtractor.Line line = txt.GetFirstLine(); line.IsValid(); line = line.GetNextLine()) { for (word = line.GetFirstWord(); word.IsValid(); word = word.GetNextWord()) { ConsoleLog += word.GetString(); } } ConsoleLog += "-----------------------------------------------------------"; } // Example 3. A more advanced text extraction example. // The output is XML structure containing paragraphs, lines, words, // as well as style and positioning information. if (example4_advanced) { Rect bbox; int cur_flow_id = -1, cur_para_id = -1; TextExtractor.Line line; TextExtractor.Word word; TextExtractor.Style s, line_style; // For each line on the page... for (line = txt.GetFirstLine(); line.IsValid(); line = line.GetNextLine()) { if (line.GetNumWords() == 0) { continue; } if (cur_flow_id != line.GetFlowID()) { if (cur_flow_id != -1) { if (cur_para_id != -1) { cur_para_id = -1; ConsoleLog += "</Para>"; } ConsoleLog += "</Flow>"; } cur_flow_id = line.GetFlowID(); ConsoleLog += "<Flow id=\"{0}\">" + cur_flow_id; } if (cur_para_id != line.GetParagraphID()) { if (cur_para_id != -1) { ConsoleLog += "</Para>"; } cur_para_id = line.GetParagraphID(); ConsoleLog += "<Para id=\"{0}\">" + cur_para_id; } bbox = line.GetBBox(); line_style = line.GetStyle(); Console.Write("<Line box=\"" + bbox.y1 + "," + bbox.y2 + "," + bbox.x1 + "," + bbox.x2 + ">"); PrintStyle(line_style); ConsoleLog += ""; // For each word in the line... for (word = line.GetFirstWord(); word.IsValid(); word = word.GetNextWord()) { // Output the bounding box for the word. bbox = word.GetBBox(); ConsoleLog += "<Word box=\"{0}, {1}, {2}, {3}\"" + bbox.x1 + bbox.y1 + bbox.x2 + bbox.y2; int sz = word.GetStringLen(); if (sz == 0) { continue; } // If the word style is different from the parent style, output the new style. s = word.GetStyle(); if (s != line_style) { PrintStyle(s); } ConsoleLog += ">\n" + word.GetString(); ConsoleLog += "</Word>"; } ConsoleLog += "</Line>"; } if (cur_flow_id != -1) { if (cur_para_id != -1) { cur_para_id = -1; ConsoleLog += "</Para>"; } ConsoleLog += "</Flow>"; } } // Note: Calling Dispose() on TextExtractor when it is not anymore in use can result in increased performance and lower memory consumption. txt.Dispose(); doc.Close(); ConsoleLog += "Done."; } catch (PDFNetException e) { ConsoleLog += e.Message; } // Sample code showing how to use low-level text extraction APIs. if (example5_low_level) { try { LowLevelTextExtractUtils util = new LowLevelTextExtractUtils(); PDFDoc doc = new PDFDoc(input_path); doc.InitSecurityHandler(); // Example 1. Extract all text content from the document ElementReader reader = new ElementReader(); PageIterator itr = doc.GetPageIterator(); //for (; itr.HasNext(); itr.Next()) // Read every page { reader.Begin(itr.Current()); LowLevelTextExtractUtils u = new LowLevelTextExtractUtils(); u.DumpAllText(reader); ConsoleLog += u.ConsoleLog; reader.End(); } // Example 2. Extract text based on the selection rectangle. ConsoleLog += "----------------------------------------------------"; ConsoleLog += "Extract text based on the selection rectangle."; ConsoleLog += "----------------------------------------------------"; Page first_page = doc.GetPage(1); string field1 = util.ReadTextFromRect(first_page, new Rect(27, 392, 563, 534), reader); string field2 = util.ReadTextFromRect(first_page, new Rect(28, 551, 106, 623), reader); string field3 = util.ReadTextFromRect(first_page, new Rect(208, 550, 387, 621), reader); ConsoleLog += "Field 1: {0}" + field1; ConsoleLog += "Field 2: {0}" + field2; ConsoleLog += "Field 3: {0}" + field3; // ... reader.Dispose(); doc.Close(); ConsoleLog += "Done."; } catch (PDFNetException e) { ConsoleLog += e.Message; } } PDFNet.Terminate(); }