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(); // 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); } }
//// GET: api/RemovePage/5 public HttpResponseMessage Get(string id) { Logging.LogErrors(ConfigurationValues.ErrorLogPath, "start page removal"); HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK); id = id + ","; PDFNet.Initialize("CT Orthopaedic Specialists(ct-ortho.com):ENTCPU:1::W:AMS(20160714):DF4FD2223CBF58B9128E100F400DD2BC2BFD701DC22C3C2E6D83F6B6F5C7"); PDFDoc newDocument = new PDFDoc(); string[] pagesToDelete = id.Split(','); DocumentRepository documentData = new DocumentRepository(); int pageCount = 0; CurrentDocuments currentDocuments = documentData.GetCurrentDocumentPathPDF(Utility.GetUserName()); string pathToCurrentPdfFile = currentDocuments.PathToCurrentPDFDocument; string pathToCurrentPdfFileTemp = pathToCurrentPdfFile.Replace(".pdf", "temp.pdf"); string pathToCurrentXodFile = documentData.GetCurrentDocumentPathXOD(Utility.GetUserName()); PDFDoc removePagesFromDocument = new PDFDoc(pathToCurrentPdfFile); pageCount = removePagesFromDocument.GetPageCount(); if (pageCount > 1) { try { Logging.LogErrors(ConfigurationValues.ErrorLogPath, "begin remove page"); PageIterator itr = removePagesFromDocument.GetPageIterator(int.Parse(pagesToDelete[0])); removePagesFromDocument.PageRemove(itr); Logging.LogErrors(ConfigurationValues.ErrorLogPath, "end remove page"); } catch (Exception er) { Logging.LogErrors(ConfigurationValues.ErrorLogPath, er.ToString()); } File.Create(pathToCurrentXodFile).Dispose(); removePagesFromDocument.Save(pathToCurrentPdfFileTemp, 0); File.Delete(pathToCurrentXodFile); pdftron.Filters.Filter objFilter = pdftron.PDF.Convert.ToXod(pathToCurrentPdfFileTemp); System.Threading.Thread.Sleep(ConfigurationValues.XodSaveDelay); objFilter.WriteToFile(pathToCurrentXodFile,true ); documentData.AddUpdateCurrentDocument(Utility.GetUserName(), pathToCurrentXodFile, pathToCurrentPdfFileTemp, currentDocuments.CurrentDocumentList, documentData.GetFullPathToDocument(Utility.GetUserName())); Logging.LogErrors(ConfigurationValues.ErrorLogPath, "open stream"); var stream = new FileStream(pathToCurrentXodFile, FileMode.Open); result.Content = new StreamContent(stream); result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); Logging.LogErrors(ConfigurationValues.ErrorLogPath, ConfigurationValues.XodFileName); result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = ConfigurationValues.XodFileName }; } Logging.LogErrors(ConfigurationValues.ErrorLogPath, "done"); return result; }
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); } }
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); } }
public string Extract(string path) { var builder = new StringBuilder(); using (var doc = new PDFDoc(path)) { doc.InitSecurityHandler(); using (TextExtractor txt = new TextExtractor()) { PageIterator itr = doc.GetPageIterator(); for (; itr.HasNext(); itr.Next()) { txt.Begin(itr.Current()); builder.AppendLine(txt.GetAsText()); } } } return(builder.ToString()); }
public void ReadTextFromCoordinates(string input_path, int pagenumber, int urx, int ury, int llx, int lly) { PDFDoc doc = new PDFDoc(input_path); doc.InitSecurityHandler(); Page page = doc.GetPage(pagenumber); ElementReader reader = new ElementReader(); PageIterator itr = doc.GetPageIterator(); reader.Begin(itr.Current()); LowLevelTextExtractUtils u = new LowLevelTextExtractUtils(); //u.DumpAllText(reader); //ConsoleLog += u.ConsoleLog; //reader.End(); string field3 = u.ReadTextFromRect(page, new Rect(urx, ury, llx, lly), reader); ConsoleLog = field3; reader.Dispose(); doc.Close(); }
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(); // Example 1: // Extract images by traversing the display list for // every page. With this approach it is possible to obtain // image positioning information and DPI. try { using (PDFDoc doc = new PDFDoc(input_path + "newsletter.pdf")) using (ElementReader reader = new ElementReader()) { doc.InitSecurityHandler(); PageIterator itr; for (itr = doc.GetPageIterator(); itr.HasNext(); itr.Next()) { reader.Begin(itr.Current()); ImageExtract(doc, reader); reader.End(); } Console.WriteLine("Done."); } } catch (PDFNetException e) { Console.WriteLine(e.Message); } Console.WriteLine("----------------------------------------------------------------"); // Example 2: // Extract images by scanning the low-level document. try { using (PDFDoc doc = new PDFDoc(input_path + "newsletter.pdf")) { doc.InitSecurityHandler(); image_counter = 0; SDFDoc cos_doc = doc.GetSDFDoc(); int num_objs = cos_doc.XRefSize(); for (int i = 1; i < num_objs; ++i) { Obj obj = cos_doc.GetObj(i); if (obj != null && !obj.IsFree() && obj.IsStream()) { // Process only images DictIterator itr = obj.Find("Subtype"); if (!itr.HasNext() || itr.Value().GetName() != "Image") { continue; } itr = obj.Find("Type"); if (!itr.HasNext() || itr.Value().GetName() != "XObject") { continue; } pdftron.PDF.Image image = new pdftron.PDF.Image(obj); Console.WriteLine("--> Image: {0}", ++image_counter); Console.WriteLine(" Width: {0}", image.GetImageWidth()); Console.WriteLine(" Height: {0}", image.GetImageHeight()); Console.WriteLine(" BPC: {0}", image.GetBitsPerComponent()); string fname = output_path + "image_extract2_" + image_counter.ToString(); image.Export(fname); // or ExporAsPng() or ExporAsTiff() ... // Convert PDF bitmap to GDI+ Bitmap... //Bitmap bmp = image.GetBitmap(); //bmp.Save(fname, ImageFormat.Png); //bmp.Dispose(); // Instead of converting PDF images to a Bitmap, you can also extract // uncompressed/compressed image data directly using element.GetImageData() // as illustrated in ElementReaderAdv sample project. } } } } catch (PDFNetException e) { Console.WriteLine(e.Message); } }
public HttpResponseMessage Get(string id) { string xodFileName = Guid.NewGuid().ToString() + ".xod"; string pdfFileName = xodFileName.Replace(".xod", ".pdf"); string filePathXod = ConfigurationValues.PathToXodFile + xodFileName; string filePathPdf = ConfigurationValues.PathToXodFile + pdfFileName; PDFNet.Initialize("CT Orthopaedic Specialists(ct-ortho.com):ENTCPU:1::W:AMS(20160714):DF4FD2223CBF58B9128E100F400DD2BC2BFD701DC22C3C2E6D83F6B6F5C7"); PDFDoc newDocument = new PDFDoc(); if (string.IsNullOrEmpty(id)) { try { File.Delete(filePathXod); } catch { } File.Create(filePathXod).Dispose(); HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK); var stream = new FileStream(filePathXod, FileMode.Open); result.Content = new StreamContent(stream); result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = ConfigurationValues.XodFileName }; return result; } else { string[] documents = id.Split('~'); for (int i = 0; i < documents.Length - 1; i++) { PDFDoc documenToAdd = new PDFDoc(ConfigurationValues.OutboundFaxDirectory + "\\" + Utility.GetUserName() + "\\" + documents[0]); PageIterator itr = documenToAdd.GetPageIterator(); for (; itr.HasNext(); itr.Next()) { try { pdftron.PDF.Page page = itr.Current(); newDocument.PageInsert(newDocument.GetPageIterator(itr.GetPageNumber()), page); } catch (Exception er) { string s1 = er.ToString(); } } } try { File.Delete(filePathXod); } catch { } DocumentData documentData = new DocumentData(); documentData.AddUpdateCurrentDocument(Utility.GetUserName(), filePathXod, filePathPdf); File.Create(filePathXod).Dispose(); newDocument.Save(filePathPdf, 0); pdftron.PDF.Convert.ToXod(newDocument, filePathXod); HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK); var stream = new FileStream(filePathXod, FileMode.Open); result.Content = new StreamContent(stream); result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = ConfigurationValues.XodFileName }; return result; } }
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(); }
/// <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 }
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); } }
// GET: api/FileFromFolder/5 public HttpResponseMessage Get(string id) { string fullPath = System.Configuration.ConfigurationManager.AppSettings["holdFolder"] + id; PDFNet.Initialize("CT Orthopaedic Specialists(ct-ortho.com):ENTCPU:1::W:AMS(20160714):DF4FD2223CBF58B9128E100F400DD2BC2BFD701DC22C3C2E6D83F6B6F5C7"); PDFDoc documentToAdd = new PDFDoc(); string xodFileName = Guid.NewGuid().ToString() + ".xod"; string pdfFileName = xodFileName.Replace(".xod", ".pdf"); string filePathXod = ConfigurationValues.PathToXodFile + xodFileName; string filePathPdf = ConfigurationValues.PathToXodFile + pdfFileName; PDFDoc newDocument = new PDFDoc(); if (string.IsNullOrEmpty(id)) { try { File.Delete(filePathXod); } catch { } File.Create(filePathXod).Dispose(); HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK); var stream = new FileStream(filePathXod, FileMode.Open); result.Content = new StreamContent(stream); result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = ConfigurationValues.XodFileName }; return result; } else { string[] documents = id.Split('~'); documentToAdd = new PDFDoc(fullPath); PageIterator itr = documentToAdd.GetPageIterator(); for (; itr.HasNext(); itr.Next()) { try { pdftron.PDF.Page page = itr.Current(); newDocument.PageInsert(newDocument.GetPageIterator(itr.GetPageNumber()), page); } catch (Exception er) { string s1 = er.ToString(); } } try { File.Delete(filePathXod); } catch { } documentToAdd.Close(); documentToAdd.Dispose(); DocumentRepository documentData = new DocumentRepository(); documentData.AddUpdateCurrentDocument(Utility.GetUserName(), filePathXod, filePathPdf, id, documentData.GetFullPathToDocument(Utility.GetUserName())); File.Create(filePathXod).Dispose(); newDocument.Save(filePathPdf, 0); pdftron.Filters.Filter objFilter = pdftron.PDF.Convert.ToXod(newDocument); System.Threading.Thread.Sleep(ConfigurationValues.XodSaveDelay); objFilter.WriteToFile(filePathXod, true); HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK); var stream = new FileStream(filePathXod, FileMode.Open); result.Content = new StreamContent(stream); result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = ConfigurationValues.XodFileName }; newDocument.Close(); newDocument.Dispose(); return result; } }
/// <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(); // Relative path to the folder containing test files string input_path = "../../TestFiles/"; string output_path = "../../TestFiles/Output/"; //Example - Exporting images of each page in the document in parallel, // and annotating the document in the main thread. try { // Open the PDF document. using (PDFDoc doc = new PDFDoc(input_path + "newsletter.pdf")) { // Lock the document, since we are going to annotate it in this thread. doc.Lock(); // Initialize the security handler, in case the PDF is encrypted. doc.InitSecurityHandler(); List <Task> tasks = new List <Task>(); // Iterate through each page in the document for (PageIterator itr = doc.GetPageIterator(); itr.HasNext(); itr.Next()) { //note that locking a second time does not cause a deadlock: doc.Lock(); // You can acquire a read lock while holding a write lock: doc.LockRead(); doc.UnlockRead(); // Choose an output path for this page string page_output_path = output_path + "newsletter_" + itr.GetPageNumber() + ".png"; // Create an asynchronous task to draw the page Page pg = itr.Current(); Task t = new Task(() => DoDraw(doc, pg, page_output_path)); // Start the Task (although it won't be able to access the document, since we have a write lock) t.Start(); // Add it to our list of Tasks so we can Wait() for it later. tasks.Add(t); Console.WriteLine("Adding stamp to PDFDoc, page " + itr.GetPageNumber()); // Create a stamp annotation (See AnnotationTest for more details) pdftron.PDF.Annots.RubberStamp stamp = pdftron.PDF.Annots.RubberStamp.Create(doc.GetSDFDoc(), new Rect(30, 30, 300, 200)); stamp.SetIcon("Approved"); itr.Current().AnnotPushBack(stamp); // Releasing the lock decrements our lock count, // but the thread still holds a write lock on the document: doc.Unlock(); } // Now we release the write lock, and the // PDFDraw tasks can begin execution doc.Unlock(); // Wait for the PDFDraw tasks to complete. foreach (Task t in tasks) { t.Wait(); } } } catch (PDFNetException e) { Console.WriteLine(e.Message); } }
/// <summary> /// The main entry point for the application. /// </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 // Extract logical structure from a PDF document { using (PDFDoc doc = new PDFDoc(input_path + "tagged.pdf")) { doc.InitSecurityHandler(); bool example1 = true; bool example2 = true; bool example3 = true; if (example1) { Console.WriteLine("____________________________________________________________"); Console.WriteLine("Sample 1 - Traverse logical structure tree..."); STree tree = doc.GetStructTree(); if (tree.IsValid()) { Console.WriteLine("Document has a StructTree root."); for (int i = 0; i < tree.GetNumKids(); ++i) { // Recursively get structure info for all all child elements. ProcessStructElement(tree.GetKid(i), 0); } } else { Console.WriteLine("This document does not contain any logical structure."); } Console.WriteLine(); Console.WriteLine("Done 1."); } if (example2) { Console.WriteLine("____________________________________________________________"); Console.WriteLine("Sample 2 - Get parent logical structure elements from"); Console.WriteLine("layout elements."); ElementReader reader = new ElementReader(); for (PageIterator itr = doc.GetPageIterator(); itr.HasNext(); itr.Next()) { reader.Begin(itr.Current()); ProcessElements(reader); reader.End(); } Console.WriteLine(); Console.WriteLine("Done 2."); } if (example3) { Console.WriteLine("____________________________________________________________"); Console.WriteLine("Sample 3 - 'XML style' extraction of PDF logical structure and page content."); //A map which maps page numbers(as Integers) //to page Maps(which map from struct mcid(as Integers) to //text Strings) Hashtable mcid_doc_map = new Hashtable(); ElementReader reader = new ElementReader(); for (PageIterator itr = doc.GetPageIterator(); itr.HasNext(); itr.Next()) { Page pg = itr.Current(); reader.Begin(pg); Hashtable page_mcid_map = new Hashtable(); mcid_doc_map.Add(pg.GetIndex(), page_mcid_map); ProcessElements2(reader, page_mcid_map); reader.End(); } STree tree = doc.GetStructTree(); if (tree.IsValid()) { for (int i = 0; i < tree.GetNumKids(); ++i) { ProcessStructElement2(tree.GetKid(i), mcid_doc_map, 0); } } Console.WriteLine(); Console.WriteLine("Done 3."); } doc.Save(output_path + "bookmark.pdf", 0); } } 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 { // Read a PDF document from a stream or pass-in a memory buffer... FileStream istm = new FileStream(input_path + "tiger.pdf", FileMode.Open, FileAccess.Read); using (PDFDoc doc = new PDFDoc(istm)) using (ElementWriter writer = new ElementWriter()) using (ElementReader reader = new ElementReader()) { doc.InitSecurityHandler(); int num_pages = doc.GetPageCount(); Element element; // Perform some document editing ... // Here we simply copy all elements from one page to another. for (int i = 1; i <= num_pages; ++i) { Page pg = doc.GetPage(2 * i - 1); reader.Begin(pg); Page new_page = doc.PageCreate(pg.GetMediaBox()); doc.PageInsert(doc.GetPageIterator(2 * i), new_page); writer.Begin(new_page); while ((element = reader.Next()) != null) // Read page contents { writer.WriteElement(element); } writer.End(); reader.End(); } doc.Save(output_path + "doc_memory_edit.pdf", SDFDoc.SaveOptions.e_remove_unused); // Save the document to a stream or a memory buffer... using (FileStream ostm = new FileStream(output_path + "doc_memory_edit.txt", FileMode.Create, FileAccess.Write)) { doc.Save(ostm, SDFDoc.SaveOptions.e_remove_unused); } // Read some data from the file stored in memory reader.Begin(doc.GetPage(1)); while ((element = reader.Next()) != null) { if (element.GetType() == Element.Type.e_path) { Console.Write("Path, "); } } reader.End(); Console.WriteLine(""); Console.WriteLine(""); Console.WriteLine("Done. Result saved in doc_memory_edit.pdf and doc_memory_edit.txt ..."); } } 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/"; // 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); } }
// GET: api/RemovePage/5 public HttpResponseMessage Get(string id) { PDFNet.Initialize("CT Orthopaedic Specialists(ct-ortho.com):ENTCPU:1::W:AMS(20160714):DF4FD2223CBF58B9128E100F400DD2BC2BFD701DC22C3C2E6D83F6B6F5C7"); PDFDoc newDocument = new PDFDoc(); string[] pagesToDelete = id.Split(','); DocumentData documentData = new DocumentData(); int pageCount = 0; string pathToCurrentPdfFile = documentData.GetCurrentDocumentPathPDF(Utility.GetUserName()); string pathToCurrentPdfFileTemp = pathToCurrentPdfFile.Replace(".pdf", "temp.pdf"); string pathToCurrentXodFile = documentData.GetCurrentDocumentPathXOD(Utility.GetUserName()); PDFDoc removePagesFromDocument = new PDFDoc(pathToCurrentPdfFile); pageCount = removePagesFromDocument.GetPageCount(); for (int i = 1; i < pageCount; i++) { try { if (int.Parse(pagesToDelete[0]) == i) { PageIterator itr = removePagesFromDocument.GetPageIterator(i); removePagesFromDocument.PageRemove(itr); } else if (int.Parse(pagesToDelete[1]) == i) { PageIterator itr = removePagesFromDocument.GetPageIterator(i); removePagesFromDocument.PageRemove(itr); } else if (int.Parse(pagesToDelete[2]) == i) { PageIterator itr = removePagesFromDocument.GetPageIterator(i); removePagesFromDocument.PageRemove(itr); } else if (int.Parse(pagesToDelete[3]) == i) { PageIterator itr = removePagesFromDocument.GetPageIterator(i); removePagesFromDocument.PageRemove(itr); } else if (int.Parse(pagesToDelete[4]) == i) { PageIterator itr = removePagesFromDocument.GetPageIterator(i); removePagesFromDocument.PageRemove(itr); } else if (int.Parse(pagesToDelete[5]) == i) { PageIterator itr = removePagesFromDocument.GetPageIterator(i); removePagesFromDocument.PageRemove(itr); } } catch { } } ////PDFDoc documenToAdd = new PDFDoc(ConfigurationValues.OutboundFaxDirectory + "\\" + Utility.GetUserName() + "\\" + documents[0]); //PageIterator itr = removePagesFromDocument.GetPageIterator(); //for (; itr.HasNext(); itr.Next()) //{ // try // { // pdftron.PDF.Page page = itr.Current(); // newDocument.PageInsert(newDocument.GetPageIterator(), page); // } // catch (Exception er) // { // string s1 = er.ToString(); // } //} //try //{ // File.Delete(pathToCurrentXodFile); //} //catch { } File.Create(pathToCurrentXodFile).Dispose(); removePagesFromDocument.Save(pathToCurrentPdfFileTemp, 0); //newDocument.Save(pathToCurrentPdfFileTemp, 0); pdftron.PDF.Convert.ToXod(pathToCurrentPdfFileTemp, pathToCurrentXodFile); HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK); var stream = new FileStream(pathToCurrentXodFile, FileMode.Open); result.Content = new StreamContent(stream); result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = ConfigurationValues.XodFileName }; return result; }
// GET: api/InboundFax/5 public HttpResponseMessage Get(string id) { HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK); try { Logging.LogErrors(ConfigurationValues.ErrorLogPath, ConfigurationValues.PdfTronLicenseKey); PDFNet.Initialize(ConfigurationValues.PdfTronLicenseKey); PDFDoc documentToAdd = new PDFDoc(); string xodFileName = Guid.NewGuid().ToString() + ".xod"; string pdfFileName = xodFileName.Replace(".xod", ".pdf"); string filePathXod = ConfigurationValues.PathToXodFile + xodFileName; string filePathPdf = ConfigurationValues.PathToXodFile + pdfFileName; PDFDoc newDocument = new PDFDoc(); if (string.IsNullOrEmpty(id)) { try { File.Delete(filePathXod); } catch { } File.Create(filePathXod).Dispose(); result = new HttpResponseMessage(HttpStatusCode.OK); var stream = new FileStream(filePathXod, FileMode.Open); result.Content = new StreamContent(stream); result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = ConfigurationValues.XodFileName }; return result; } else { string[] documents = id.Split('~'); for (int i = 0; i < documents.Length - 1; i++) { FaxRepository faxData = new FaxRepository(); //documentToAdd = new PDFDoc(faxData.GetFullPathInboundFax(documents[i])); documentToAdd = new PDFDoc(documents[i]); PageIterator itr = documentToAdd.GetPageIterator(); for (; itr.HasNext(); itr.Next()) { try { pdftron.PDF.Page page = itr.Current(); newDocument.PageInsert(newDocument.GetPageIterator(itr.GetPageNumber()), page); } catch (Exception er) { string s1 = er.ToString(); } } } try { File.Delete(filePathXod); } catch { } documentToAdd.Close(); documentToAdd.Dispose(); DocumentRepository documentData = new DocumentRepository(); documentData.AddUpdateCurrentDocument(Utility.GetUserName(), filePathXod, filePathPdf, id, documentData.GetFullPathToDocument(Utility.GetUserName())); File.Create(filePathXod).Dispose(); newDocument.Save(filePathPdf, 0); pdftron.Filters.Filter objFilter = pdftron.PDF.Convert.ToXod(newDocument); System.Threading.Thread.Sleep(ConfigurationValues.XodSaveDelay); objFilter.WriteToFile(filePathXod, true); var stream = new FileStream(filePathXod, FileMode.Open); result.Content = new StreamContent(stream); result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = ConfigurationValues.XodFileName }; newDocument.Close(); newDocument.Dispose(); } return result; } catch (Exception er) { Logging.LogErrors(ConfigurationValues.ErrorLogPath, er.ToString()); return result; } }
static void Main(string[] args) { PDFNet.Initialize(); // Relative path to the folder containing test files. string input_path = "../../TestFiles/"; bool example1_basic = false; bool example2_xml = false; bool example3_wordlist = false; bool example4_advanced = true; bool example5_low_level = false; // Sample code showing how to use high-level text extraction APIs. try { using (PDFDoc doc = new PDFDoc(input_path + "newsletter.pdf")) { doc.InitSecurityHandler(); Page page = doc.GetPage(1); if (page == null) { Console.WriteLine("Page not found."); return; } using (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. Console.WriteLine("Word Count: {0}", txt.GetWordCount()); Console.WriteLine("\n\n- GetAsText --------------------------\n{0}", txt.GetAsText()); Console.WriteLine("-----------------------------------------------------------"); } // 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); Console.WriteLine("\n\n- GetAsXML --------------------------\n{0}", text); Console.WriteLine("-----------------------------------------------------------"); } // 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()) { Console.WriteLine(word.GetString()); } } Console.WriteLine("-----------------------------------------------------------"); } // 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; Console.WriteLine("<PDFText>"); // 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; Console.WriteLine("</Para>"); } Console.WriteLine("</Flow>"); } cur_flow_id = line.GetFlowID(); Console.WriteLine("<Flow id=\"{0}\">", cur_flow_id); } if (cur_para_id != line.GetParagraphID()) { if (cur_para_id != -1) { Console.WriteLine("</Para>"); } cur_para_id = line.GetParagraphID(); Console.WriteLine("<Para id=\"{0}\">", cur_para_id); } bbox = line.GetBBox(); line_style = line.GetStyle(); Console.Write("<Line box=\"{0}, {1}, {2}, {3}\"", bbox.x1.ToString("0.00"), bbox.y1.ToString("0.00"), bbox.x2.ToString("0.00"), bbox.y2.ToString("0.00")); PrintStyle(line_style); Console.Write(" cur_num=\"" + line.GetCurrentNum() + "\"" + ">\n"); // 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(); Console.Write("<Word box=\"{0}, {1}, {2}, {3}\"", bbox.x1.ToString("0.00"), bbox.y1.ToString("0.00"), bbox.x2.ToString("0.00"), bbox.y2.ToString("0.00")); Console.Write(" cur_num=\"" + word.GetCurrentNum() + "\""); 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); } Console.Write(">{0}", word.GetString()); Console.WriteLine("</Word>"); } Console.WriteLine("</Line>"); } if (cur_flow_id != -1) { if (cur_para_id != -1) { cur_para_id = -1; Console.WriteLine("</Para>"); } Console.WriteLine("</Flow>"); } } } Console.WriteLine("</PDFText>"); } } catch (PDFNetException e) { Console.WriteLine(e.Message); } // Sample code showing how to use low-level text extraction APIs. if (example5_low_level) { try { LowLevelTextExtractUtils util = new LowLevelTextExtractUtils(); using (PDFDoc doc = new PDFDoc(input_path + "newsletter.pdf")) { doc.InitSecurityHandler(); // Example 1. Extract all text content from the document using (ElementReader reader = new ElementReader()) { PageIterator itr = doc.GetPageIterator(); //for (; itr.HasNext(); itr.Next()) // Read every page { reader.Begin(itr.Current()); LowLevelTextExtractUtils.DumpAllText(reader); reader.End(); } // Example 2. Extract text based on the selection rectangle. Console.WriteLine("----------------------------------------------------"); Console.WriteLine("Extract text based on the selection rectangle."); Console.WriteLine("----------------------------------------------------"); 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); Console.WriteLine("Field 1: {0}", field1); Console.WriteLine("Field 2: {0}", field2); Console.WriteLine("Field 3: {0}", field3); // ... Console.WriteLine("Done."); } } } catch (PDFNetException e) { Console.WriteLine(e.Message); } } }
void Execute(string[] args) { PDFNet.Initialize(); // 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. try { // PDFNet.SetColorManagement(); // PDFNet.SetDefaultDeviceCMYKProfile("USWebCoatedSWOP.icc"); // will search in PDFNet resource folder. // PDFNet.SetDefaultDeviceRGBProfile("AdobeRGB1998.icc"); } catch (Exception) { Console.WriteLine("The specified color profile was not found."); } // 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"); string input_path = "../../TestFiles/"; // Relative path to the folder containing test files. try { // Open the PDF document. Console.WriteLine("Opening the input file..."); using (pdfdoc = new PDFDoc(input_path + "tiger.pdf")) { pdfdoc.InitSecurityHandler(); ////////////////////////////////////////////////////////////////////////// // Example 1: use the PDF::Print::StartPrintJob interface // This is silent (no progress dialog) and blocks until print job is at spooler // The rasterized print job is compressed before sending to printer Console.WriteLine("Printing the input file using PDF.Print.StartPrintJob..."); // Setup printing options: PrinterMode printerMode = new PrinterMode(); printerMode.SetAutoCenter(true); printerMode.SetAutoRotate(true); printerMode.SetCollation(true); printerMode.SetCopyCount(1); printerMode.SetDPI(300); // regardless of ordering, an explicit DPI setting overrides the OutputQuality setting printerMode.SetDuplexing(PrinterMode.DuplexMode.e_Duplex_Auto); printerMode.SetNUp(PrinterMode.NUp.e_NUp_1_1, PrinterMode.NUpPageOrder.e_PageOrder_LeftToRightThenTopToBottom); printerMode.SetOrientation(PrinterMode.Orientation.e_Orientation_Portrait); printerMode.SetOutputAnnot(PrinterMode.PrintContentTypes.e_PrintContent_DocumentAndAnnotations); // If the XPS print path is being used, then the printer spooler file will // ignore the grayscale option and be in full color printerMode.SetOutputColor(PrinterMode.OutputColor.e_OutputColor_Grayscale); printerMode.SetOutputPageBorder(false); printerMode.SetOutputQuality(PrinterMode.OutputQuality.e_OutputQuality_Medium); printerMode.SetPaperSize(new Rect(0, 0, 612, 792)); PageSet pagesToPrint = new PageSet(1, pdfdoc.GetPageCount(), PageSet.Filter.e_all); // You can get the name of the default printer by using: // PrinterSettings ps = new PrinterSettings(); // String printerName ps.PrinterName(); // however Print.StartPrintJob can also determine this for you, just pass an empty printer name // Print the document on the default printer, name the print job the name of the // file, print to the printer not a file, and use printer options: Print.StartPrintJob(pdfdoc, "", pdfdoc.GetFileName(), "", pagesToPrint, printerMode, null); ////////////////////////////////////////////////////////////////////////// // Example 2: use the .Net PrintDocument class and PDFDraw rasterizer // This will pop up a progress dialog // Start printing from the first page pageitr = pdfdoc.GetPageIterator(); pdfdraw = new PDFDraw(); pdfdraw.SetPrintMode(true); pdfdraw.SetRasterizerType(PDFRasterizer.Type.e_BuiltIn); // Create a printer PrintDocument printer = new PrintDocument(); // name the document to be printed printer.DocumentName = pdfdoc.GetFileName(); // Set the PrintPage delegate which will be invoked to print each page printer.PrintPage += new PrintPageEventHandler(PrintPage); Console.WriteLine("Printing the input file using .NET PrintDocument and PDFDraw..."); printer.Print(); // Start printing pdfdraw.Dispose(); // Free allocated resources (generally a good idea when printing many documents). } } catch (PDFNetException e) { Console.WriteLine(e.Message); } }
private static void AnnotationHighLevelAPI(PDFDoc doc) { // The following code snippet traverses all annotations in the document System.Console.WriteLine("Traversing all annotations in the document..."); string uri; int page_num = 1; for (PageIterator itr = doc.GetPageIterator(); itr.HasNext(); itr.Next()) { System.Console.WriteLine("Page " + page_num++ + ": "); Page page = itr.Current(); int num_annots = page.GetNumAnnots(); for (int i = 0; i < num_annots; ++i) { Annot annot = page.GetAnnot(i); if (!annot.IsValid()) { continue; } System.Console.WriteLine("Annot Type: " + annot.GetSDFObj().Get("Subtype").Value().GetName()); Rect bbox = annot.GetRect(); System.Console.WriteLine(" Position: " + bbox.x1 + ", " + bbox.y1 + ", " + bbox.x2 + ", " + bbox.y2); switch (annot.GetType()) { case Annot.Type.e_Link: { Link lnk = new Link(annot); Action action = lnk.GetAction(); if (!action.IsValid()) { continue; } if (action.GetType() == Action.Type.e_GoTo) { Destination dest = action.GetDest(); if (!dest.IsValid()) { System.Console.WriteLine(" Destination is not valid"); } else { int pg_num = dest.GetPage().GetIndex(); System.Console.WriteLine(" Links to: page number " + pg_num + " in this document"); } } else if (action.GetType() == Action.Type.e_URI) { uri = action.GetSDFObj().Get("URI").Value().GetAsPDFText(); System.Console.WriteLine(" Links to: " + uri); } // ... } break; case Annot.Type.e_Widget: break; case Annot.Type.e_FileAttachment: break; // ... default: break; } } } // Use the high-level API to create new annotations. Page first_page = doc.GetPage(1); // Create a hyperlink... Link hyperlink = Link.Create(doc, new Rect(85, 570, 503, 524), Action.CreateURI(doc, "http://www.pdftron.com")); first_page.AnnotPushBack(hyperlink); // Create an intra-document link... Action goto_page_3 = Action.CreateGoto(Destination.CreateFitH(doc.GetPage(3), 0)); Link link = Link.Create(doc, new Rect(85, 458, 503, 502), goto_page_3); // Set the annotation border width to 3 points... Annot.BorderStyle border_style = new Annot.BorderStyle(Annot.BorderStyle.Style.e_solid, 3, 0, 0); //link.SetBorderStyle(border_style); link.SetColor(new ColorPt(0, 0, 1)); // Add the new annotation to the first page first_page.AnnotPushBack(link); // Create a stamp annotation ... RubberStamp stamp = RubberStamp.Create(doc, new Rect(30, 30, 300, 200)); stamp.SetIcon("Draft"); first_page.AnnotPushBack(stamp); // Create a file attachment annotation (embed the 'peppers.jpg'). FileAttachment file_attach = FileAttachment.Create(doc, new Rect(80, 280, 200, 320), (input_path + "peppers.jpg")); first_page.AnnotPushBack(file_attach); Ink ink = Ink.Create(doc, new Rect(110, 10, 300, 200)); Point pt3 = new 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); first_page.AnnotPushBack(ink); }