public List <PdfString> RegexSearch(PDFDoc doc, string pattern, bool ifWholeWord, int startPage, int endPage, bool ignoreCase) { List <PdfString> result = new List <PdfString>(); Int32 page_num = 0; string result_str = ""; string ambient_string = ""; Highlights hlts = new Highlights(); Int32 mode = (Int32)(TextSearch.SearchMode.e_reg_expression | TextSearch.SearchMode.e_highlight); if (ifWholeWord) { mode |= (Int32)TextSearch.SearchMode.e_whole_word; } if (ignoreCase) { mode |= (Int32)TextSearch.SearchMode.e_case_sensitive; } int pageCount = doc.GetPageCount(); if (endPage > pageCount) { endPage = pageCount; } TextSearch txt_search = new TextSearch(); txt_search.Begin(doc, pattern, mode, startPage, endPage); while (true) { TextSearch.ResultCode code = txt_search.Run(ref page_num, ref result_str, ref ambient_string, hlts); if (code == TextSearch.ResultCode.e_found) { hlts.Begin(doc); double[] box = null; string temp = result_str; while (hlts.HasNext()) { box = hlts.GetCurrentQuads(); if (box.Length != 8) { hlts.Next(); continue; } result.Add(new PdfString(result_str, new Rect(box[0], box[1], box[4], box[5]), page_num)); hlts.Next(); } } else if (code == TextSearch.ResultCode.e_done) { break; } } return(result); }
public FileItemDTO CompressFile(FileItemEntity fileItem) { fileItem.FileFullPath = FileUtils.GetDefaultInputPath() + fileItem.FileName; File.WriteAllBytes(fileItem.FileFullPath, fileItem.Bytes); var fileItemDTO = new FileItemDTO() { Id = fileItem.Id, FileFullPath = FileUtils.GetNewFileName(fileItem.FileName, FileNameOptionEnum.Compress) }; fileItemDTO.FileName = FileUtils.GetSafeFileName(fileItemDTO.FileFullPath); using (PDFDoc in_doc = new PDFDoc(fileItem.FileFullPath)) { Optimizer.Optimize(in_doc); using (PDFDoc doc = new PDFDoc()) { doc.InsertPages(doc.GetPageCount() + 1, in_doc, 1, in_doc.GetPageCount(), PDFDoc.InsertFlag.e_none); in_doc.Save(fileItemDTO.FileFullPath, SDFDoc.SaveOptions.e_linearized); } } return(fileItemDTO); }
private List <LineFound> GetValue(PDFDoc doc, PdfString ricPosition, string patternRic, string patternValue) { List <LineFound> bulkFile = new List <LineFound>(); try { List <string> line = new List <string>(); List <PdfString> ric = null; //for (int i = 1; i < 10; i++) for (int i = 1; i < doc.GetPageCount(); i++) { ric = pa.RegexExtractByPositionWithPage(doc, patternRic, i, ricPosition.Position); foreach (var item in ric) { LineFound lineFound = new LineFound(); lineFound.Ric = item.Words.ToString(); lineFound.Position = item.Position; lineFound.PageNumber = i; lineFound.LineData = pa.RegexExtractByPositionWithPage(doc, patternValue, i, item.Position, PositionRect.X2); bulkFile.Add(lineFound); } } } catch (Exception ex) { string msg = string.Format("\r\n ClassName: {0}\r\n MethodName: {1}\r\n Message: {2}", System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.ToString(), System.Reflection.MethodBase.GetCurrentMethod().Name, ex.Message); Logger.Log(msg, Logger.LogType.Error); } return(bulkFile); }
//// 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; }
private LinePos GetSearchTextResult(string searchText, string verifyText, ref LinePos lowRange, bool isTableName) { try { bool isDone = false; int startPage = pdfTronHelper.GetLowPage(lowRange); while (!isDone) { List <LinePos> linePoses = pdfTronHelper.Search(searchText, lowRange, null, ref startPage); if (linePoses.Count > 0) { foreach (LinePos linePos in linePoses) { if (!Regex.IsMatch(linePos.TrimText, verifyText)) { continue; } if (isTableName) { string tableNameNearbyRegex = _locateConfiguration.TableNameNearbyRegex; string tableNameNearbyFirstLetterRegex = _locateConfiguration.TableNameNearbyFirstLetterRegex; LinePos linePosCopy = (LinePos)linePos.Clone(); string nearByRegexExpression = tableNameNearbyRegex; LinePos tableNearbyPos = GetSearchTextResult(nearByRegexExpression, nearByRegexExpression, ref linePosCopy, false); if (tableNearbyPos == null) { LinePos lowRangeCopy2 = (LinePos)linePos.Clone(); tableNearbyPos = GetSearchTextResult(tableNameNearbyFirstLetterRegex, nearByRegexExpression, ref lowRangeCopy2, false); } if (tableNearbyPos == null || !ValidateTableNameNearbyPos(linePos, tableNearbyPos)) { continue; } } lowRange = new LinePos() { PageNum = linePos.PageNum, AxisValue = linePos.AxisValue + GetError(true, linePos.PageNum), TrimText = linePos.TrimText }; linePos.AxisValue = linePos.AxisValueWithLineHeight; return(linePos); } } isDone = startPage > pdfDoc.GetPageCount(); } } catch (Exception ex) { string err = ex.ToString(); throw; } return(null); }
/// <summary> /// Get the pos of the bottom bound of a pdf page. /// </summary> /// <param name="pageNum">The number of the pdf page.</param> /// <returns>Return the pos of the bottom bound of a pdf page.</returns> public LinePos GetBottomPosOfPage(int pageNum, bool isMatchNum, double lowPos, double highPos) { if (pageNum > _pdfDoc.GetPageCount() || pageNum < 1) { return(null); } LinePos linePos = new LinePos() { PageNum = pageNum }; linePos.AxisValue = linePos.AxisValueWithLineHeight = GetBottomTextYValue(pageNum, lowPos == -1?0:lowPos, highPos == -1?GetTopPosOfPage(pageNum).AxisValue:highPos, isMatchNum); return(linePos); }
private void btnCombPdf_Click(object sender, EventArgs e) { ofdAbrirArquivo.Multiselect = true; if (ofdAbrirArquivo.ShowDialog() == DialogResult.OK) { var mergedFileName = GetFilePath(ofdAbrirArquivo.FileNames[0]) + string.Join('_', ofdAbrirArquivo.SafeFileNames.Select(x => x.TrimEnd(".pdf".ToCharArray()))); try { using (PDFDoc new_doc = new PDFDoc()) { new_doc.InitSecurityHandler(); foreach (var input_doc in ofdAbrirArquivo.FileNames) { using (PDFDoc in_doc = new PDFDoc(input_doc)) { in_doc.InitSecurityHandler(); new_doc.InsertPages(new_doc.GetPageCount() + 1, in_doc, 1, in_doc.GetPageCount(), PDFDoc.InsertFlag.e_none); } } //Era pra funcionar, mas lança uma exceção no método "new_doc.ImportPages" //ArrayList copy_pages = new ArrayList(); //for (PageIterator itr = in_doc.GetPageIterator(); itr.HasNext(); itr.Next()) //{ // copy_pages.Add(itr.Current()); //} //var imported_pages = new_doc.ImportPages(copy_pages, false); //for (int i = 0; i != imported_pages.Count; ++i) //{ // new_doc.PagePushBack((Page)imported_pages[i]); //} new_doc.Save(GetNewFileName(mergedFileName, FileNameOptionEnum.Merge), SDFDoc.SaveOptions.e_linearized); } } catch (PDFNetException ex) { MessageBox.Show(ex.Message); } catch (Exception ex) { MessageBox.Show(ex.Message); } } }
/// <summary> /// Insert file should have name insertPage.pdf /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void AddNewPageButton_Click(object sender, RoutedEventArgs e) { string insertNewPath = Path.Combine(Windows.Storage.ApplicationData.Current.TemporaryFolder.Path, "insertPage.pdf"); using (var pdfDoc = new PDFDoc(insertNewPath)) { var doc = mPdfViewCtrl.GetDoc(); doc.InsertPages(1, pdfDoc, 1, pdfDoc.GetPageCount(), PDFDocInsertFlag.e_none); mPdfViewCtrl.Update(); mPdfViewCtrl.UpdateLayout(); await Save(); } }
/// <summary> /// resave first page. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void resavePageButton_Click(object sender, RoutedEventArgs e) { using (var pdfDoc = new PDFDoc()) { var doc = mPdfViewCtrl.GetDoc(); var firstPage = doc.GetPage(1); pdfDoc.PagePushFront(firstPage); doc.PageRemove(doc.GetPageIterator(1)); doc.InsertPages(1, pdfDoc, 1, pdfDoc.GetPageCount(), PDFDocInsertFlag.e_none); mPdfViewCtrl.Update(); mPdfViewCtrl.UpdateLayout(); } }
public List <PdfString> RegexSearchByPage(PDFDoc doc, string pattern, int pageIndex) { if (pageIndex > doc.GetPageCount()) { throw new Exception("pageIndex out of MaxRange of pdf."); } if (pageIndex < 1) { throw new Exception("pageIndex out of MixRange of pdf."); } return(RegexSearch(doc, pattern, false, pageIndex, pageIndex, true)); }
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)); } } }
private void btnCompriPdf_Click(object sender, EventArgs e) { if (ofdAbrirArquivo.ShowDialog() == DialogResult.OK) { using (PDFDoc doc = new PDFDoc(ofdAbrirArquivo.FileName)) { Optimizer.Optimize(doc); using (PDFDoc newDoc = new PDFDoc()) { newDoc.InsertPages(newDoc.GetPageCount() + 1, doc, 1, doc.GetPageCount(), PDFDoc.InsertFlag.e_none); newDoc.Save(GetNewFileName(ofdAbrirArquivo.FileName, FileNameOptionEnum.Compress), SDFDoc.SaveOptions.e_linearized); } } } }
private void btnCopiaPdf_Click(object sender, EventArgs e) { if (ofdAbrirArquivo.ShowDialog() == DialogResult.OK) { using (PDFDoc in_doc = new PDFDoc(ofdAbrirArquivo.FileName)) { using (PDFDoc copy_doc = new PDFDoc()) { copy_doc.InitSecurityHandler(); copy_doc.InsertPages(copy_doc.GetPageCount() + 1, in_doc, 1, in_doc.GetPageCount(), PDFDoc.InsertFlag.e_none); copy_doc.Save(GetNewFileName(ofdAbrirArquivo.FileName, FileNameOptionEnum.Copy), SDFDoc.SaveOptions.e_linearized); } } } }
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); } }
private static void WatermarkFile(PDFDoc doc, WaterMarkInfo watermarkInfo) { using (var stamp = new Stamper(Stamper.SizeType.e_relative_scale, 1, 1)) { doc.InitSecurityHandler(); stamp.SetAlignment(Stamper.HorizontalAlignment.e_horizontal_center, Stamper.VerticalAlignment.e_vertical_center); stamp.SetFontColor(new ColorPt(0, 0, 0)); // set text color to red stamp.SetOpacity(0.1); stamp.SetRotation(-67); stamp.ShowsOnPrint(true); stamp.ShowsOnScreen(true); stamp.SetAsBackground(false); stamp.StampText(doc, watermarkInfo.CustomMessage + "\n" + watermarkInfo.UserIPAddress, new PageSet(1, doc.GetPageCount())); } }
public Bitmap ToBitmap(string pdfFile) { Bitmap bitmap = null; using (PDFDoc doc = new PDFDoc(pdfFile)) { foxit.common.ErrorCode error_code = doc.Load(null); if (error_code == foxit.common.ErrorCode.e_ErrSuccess) { // Console.WriteLine("The PDFDoc [{0}] Error: {1}\n", pdfFile, error_code); //} //else //{ int nPageCount = doc.GetPageCount(); for (int i = 0; i < nPageCount; i++) { using (PDFPage page = doc.GetPage(i)) { // Parse page. page.StartParse((int)foxit.pdf.PDFPage.ParseFlags.e_ParsePageNormal, null, false); int width = (int)(page.GetWidth()) * 600 / 96; int height = (int)(page.GetHeight()) * 600 / 96; Matrix2D matrix = page.GetDisplayMatrix(0, 0, width, height, page.GetRotation()); // Prepare a bitmap for rendering. bitmap = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppArgb); bitmap.SetResolution((float)600, (float)600); using (Graphics draw = Graphics.FromImage(bitmap)) { draw.Clear(Color.White); // Render page foxit.common.Renderer render = new foxit.common.Renderer(bitmap, false); render.StartRender(page, matrix, null); } } } } } return(bitmap); }
public List <PdfString> RegexSearchByPageRange(PDFDoc doc, string pattern, int startPage, int endPage) { if (endPage > doc.GetPageCount()) { throw new Exception("endPage out of MaxRange of pdf."); } if (startPage < 1) { throw new Exception("startPage out of MixRange of pdf."); } if (startPage > endPage) { throw new Exception("pageRange is invalid."); } return(RegexSearch(doc, pattern, false, startPage, endPage, true)); }
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); } }
// 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; }
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); } }
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); } }
static void Main(string[] args) { PDFNet.Initialize(); try { //----------------------------------------------------------- // Example 1: Add page labels to an existing or newly created PDF // document. //----------------------------------------------------------- { using (PDFDoc doc = new PDFDoc(input_path + "newsletter.pdf")) { doc.InitSecurityHandler(); // Create a page labeling scheme that starts with the first page in // the document (page 1) and is using uppercase roman numbering // style. doc.SetPageLabel(1, PageLabel.Create(doc, PageLabel.Style.e_roman_uppercase, "My Prefix ", 1)); // Create a page labeling scheme that starts with the fourth page in // the document and is using decimal arabic numbering style. // Also the numeric portion of the first label should start with number // 4 (otherwise the first label would be "My Prefix 1"). PageLabel L2 = PageLabel.Create(doc, PageLabel.Style.e_decimal, "My Prefix ", 4); doc.SetPageLabel(4, L2); // Create a page labeling scheme that starts with the seventh page in // the document and is using alphabetic numbering style. The numeric // portion of the first label should start with number 1. PageLabel L3 = PageLabel.Create(doc, PageLabel.Style.e_alphabetic_uppercase, "My Prefix ", 1); doc.SetPageLabel(7, L3); doc.Save(output_path + "newsletter_with_pagelabels.pdf", SDFDoc.SaveOptions.e_linearized); Console.WriteLine("Done. Result saved in newsletter_with_pagelabels.pdf..."); } } //----------------------------------------------------------- // Example 2: Read page labels from an existing PDF document. //----------------------------------------------------------- { using (PDFDoc doc = new PDFDoc(output_path + "newsletter_with_pagelabels.pdf")) { doc.InitSecurityHandler(); PageLabel label; int page_num = doc.GetPageCount(); for (int i = 1; i <= page_num; ++i) { Console.Write("Page number: {0}", i); label = doc.GetPageLabel(i); if (label.IsValid()) { Console.WriteLine(" Label: {0}", label.GetLabelTitle(i)); } else { Console.WriteLine(" No Label."); } } } } //----------------------------------------------------------- // Example 3: Modify page labels from an existing PDF document. //----------------------------------------------------------- { using (PDFDoc doc = new PDFDoc(output_path + "newsletter_with_pagelabels.pdf")) { doc.InitSecurityHandler(); // Remove the alphabetic labels from example 1. doc.RemovePageLabel(7); // Replace the Prefix in the decimal lables (from example 1). PageLabel label = doc.GetPageLabel(4); if (label.IsValid()) { label.SetPrefix("A"); label.SetStart(1); } // Add a new label PageLabel new_label = PageLabel.Create(doc, PageLabel.Style.e_decimal, "B", 1); doc.SetPageLabel(10, new_label); // starting from page 10. doc.Save(output_path + "newsletter_with_pagelabels_modified.pdf", SDFDoc.SaveOptions.e_linearized); Console.WriteLine("Done. Result saved in newsletter_with_pagelabels_modified.pdf..."); int page_num = doc.GetPageCount(); for (int i = 1; i <= page_num; ++i) { Console.Write("Page number: {0}", i); label = doc.GetPageLabel(i); if (label.IsValid()) { Console.WriteLine(" Label: {0}", label.GetLabelTitle(i)); } else { Console.WriteLine(" No Label."); } } } } //----------------------------------------------------------- // Example 4: Delete all page labels in an existing PDF document. //----------------------------------------------------------- { using (PDFDoc doc = new PDFDoc(output_path + "newsletter_with_pagelabels.pdf")) { doc.GetRoot().Erase("PageLabels"); // ... } } } catch (pdftron.Common.PDFNetException e) { Console.WriteLine(e.Message); } }
static void Main(string[] args) { var builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true); IConfiguration configuration = builder.Build(); Log.Logger = new LoggerConfiguration() .WriteTo.File("ExtractPDF.log") .ReadFrom.Configuration(configuration) .CreateLogger(); var serviceCollection = new ServiceCollection(); ConfigureServices(serviceCollection, configuration); var serviceProvider = serviceCollection.BuildServiceProvider(); var logger = serviceProvider.GetService <ILogger <Program> >(); var filepath = configuration.GetSection("PDFConfig").GetValue <string>("Path"); PDFNet.Initialize(); // it is container of data. it will be used in parsing engine. List <Helper.LineDataOfPage> lstPages = new List <Helper.LineDataOfPage>(); using (PDFDoc doc = new PDFDoc(filepath)) //using (PDFDoc doc = new PDFDoc("Article Dev Data Set.pdf")) { doc.InitSecurityHandler(); int pagecount = doc.GetPageCount(); for (int i = 1; i <= pagecount; i++) { Page page = doc.GetPage(i); //Get Page Data if (page == null) { logger.LogError("Page not found."); continue; } using (TextExtractor txt = new TextExtractor()) { txt.Begin(page); // Read the page. // Get XML Content from the page String text = txt.GetAsXML(TextExtractor.XMLOutputFlags.e_words_as_elements | TextExtractor.XMLOutputFlags.e_output_bbox | TextExtractor.XMLOutputFlags.e_output_style_info); XmlSerializer serializer = new XmlSerializer(typeof(Helper.Page)); Helper.Page pg; using (TextReader reader = new StringReader(text)) { // Deserializing XML content. pg = (Helper.Page)serializer.Deserialize(reader); // add pre-processed data to container. lstPages.Add(Helper.Helper.ConvertPageToProcessingLineData(pg)); } } } } // Run parsing module. ParsingService ps = serviceProvider.GetService <ParsingService>(); ps.Process(lstPages); }
private void btnNovoPdf_Click(object sender, System.EventArgs e) { // Using PDFNet related classes and methods, must // catch or throw PDFNetException try { using (PDFDoc doc = new PDFDoc()) { using (Stamper s = new Stamper(Stamper.SizeType.e_relative_scale, 0.5, 0.5)) { var randomNumber = new Random().Next(0, System.Convert.ToInt32(tbxNumMaxArquivos.Text)); doc.InitSecurityHandler(); // An example of creating a new page and adding it to // doc's sequence of pages Page newPg = doc.PageCreate(); doc.PagePushBack(newPg); s.SetAlignment(Stamper.HorizontalAlignment.e_horizontal_center, Stamper.VerticalAlignment.e_vertical_center); s.SetFontColor(new ColorPt(1, 0, 0)); // set text color to red s.StampText(doc, $"{tbxDefaultNewName.Text} document {randomNumber}", new PageSet(1, doc.GetPageCount())); var caminhoDestino = chkGerarWatchFolder.Checked ? CONVERTER_DEFAULT_OUTPUT_PATH : fbdCaminhoPasta.SelectedPath; // Save as a linearized file which is most popular // and effective format for quick PDF Viewing. doc.Save(caminhoDestino + $"\\{tbxDefaultNewName.Text}_{randomNumber}.pdf", SDFDoc.SaveOptions.e_linearized); } } } catch (PDFNetException ex) { MessageBox.Show(ex.Message); } }
/// <summary> // The following sample shows how to add new content (or watermark) PDF pages // using 'pdftron.PDF.Stamper' utility class. // // Stamper can be used to PDF pages with text, images, or with other PDF content // in only a few lines of code. Although Stamper is very simple to use compared // to ElementBuilder/ElementWriter it is not as powerful or flexible. In case you // need full control over PDF creation use ElementBuilder/ElementWriter to add // new content to existing PDF pages as shown in the ElementBuilder sample project. /// </summary> static void Main(string[] args) { PDFNet.Initialize(); string input_path = "../../TestFiles/"; string output_path = "../../TestFiles/Output/"; string input_filename = "newsletter"; //-------------------------------------------------------------------------------- // Example 1) Add text stamp to all pages, then remove text stamp from odd pages. try { using (PDFDoc doc = new PDFDoc(input_path + input_filename + ".pdf")) using (Stamper s = new Stamper(Stamper.SizeType.e_relative_scale, 0.5, 0.5)) { doc.InitSecurityHandler(); s.SetAlignment(Stamper.HorizontalAlignment.e_horizontal_center, Stamper.VerticalAlignment.e_vertical_center); s.SetFontColor(new ColorPt(1, 0, 0)); // set text color to red s.StampText(doc, "If you are reading this\nthis is an even page", new PageSet(1, doc.GetPageCount())); //delete all text stamps in odd pages Stamper.DeleteStamps(doc, new PageSet(1, doc.GetPageCount(), PageSet.Filter.e_odd)); doc.Save(output_path + input_filename + ".ex1.pdf", SDFDoc.SaveOptions.e_linearized); } } catch (PDFNetException e) { Console.WriteLine(e.Message); } //-------------------------------------------------------------------------------- // Example 2) Add Image stamp to first 2 pages. try { using (PDFDoc doc = new PDFDoc(input_path + input_filename + ".pdf")) using (Stamper s = new Stamper(Stamper.SizeType.e_relative_scale, .05, .05)) { doc.InitSecurityHandler(); Image img = Image.Create(doc, input_path + "peppers.jpg"); s.SetSize(Stamper.SizeType.e_relative_scale, 0.5, 0.5); //set position of the image to the center, left of PDF pages s.SetAlignment(Stamper.HorizontalAlignment.e_horizontal_left, Stamper.VerticalAlignment.e_vertical_center); s.SetFontColor(new ColorPt(0, 0, 0, 0)); s.SetRotation(180); s.SetAsBackground(false); //only stamp first 2 pages s.StampImage(doc, img, new PageSet(1, 2)); doc.Save(output_path + input_filename + ".ex2.pdf", SDFDoc.SaveOptions.e_linearized); } } catch (PDFNetException e) { Console.WriteLine(e.Message); } //-------------------------------------------------------------------------------- // Example 3) Add Page stamp to all pages. try { using (PDFDoc doc = new PDFDoc(input_path + input_filename + ".pdf")) using (PDFDoc fish_doc = new PDFDoc(input_path + "fish.pdf")) using (Stamper s = new Stamper(Stamper.SizeType.e_relative_scale, .5, .5)) { doc.InitSecurityHandler(); fish_doc.InitSecurityHandler(); Page src_page = fish_doc.GetPage(1); Rect page_one_crop = src_page.GetCropBox(); // set size of the image to 10% of the original while keep the old aspect ratio s.SetSize(Stamper.SizeType.e_absolute_size, page_one_crop.Width() * 0.1, -1); s.SetOpacity(0.4); s.SetRotation(-67); //put the image at the bottom right hand corner s.SetAlignment(Stamper.HorizontalAlignment.e_horizontal_right, Stamper.VerticalAlignment.e_vertical_bottom); s.StampPage(doc, src_page, new PageSet(1, doc.GetPageCount())); doc.Save(output_path + input_filename + ".ex3.pdf", SDFDoc.SaveOptions.e_linearized); } } catch (PDFNetException e) { Console.WriteLine(e.Message); } //-------------------------------------------------------------------------------- // Example 4) Add Image stamp to first 20 odd pages. try { using (PDFDoc doc = new PDFDoc(input_path + input_filename + ".pdf")) using (Stamper s = new Stamper(Stamper.SizeType.e_absolute_size, 20, 20)) { doc.InitSecurityHandler(); s.SetOpacity(1); s.SetRotation(45); s.SetAsBackground(true); s.SetPosition(30, 40); Image img = Image.Create(doc, input_path + "peppers.jpg"); s.StampImage(doc, img, new PageSet(1, 20, PageSet.Filter.e_odd)); doc.Save(output_path + input_filename + ".ex4.pdf", SDFDoc.SaveOptions.e_linearized); } } catch (PDFNetException e) { Console.WriteLine(e.Message); } //-------------------------------------------------------------------------------- // Example 5) Add text stamp to first 20 even pages try { using (PDFDoc doc = new PDFDoc(input_path + input_filename + ".pdf")) using (Stamper s = new Stamper(Stamper.SizeType.e_relative_scale, .05, .05)) { doc.InitSecurityHandler(); s.SetPosition(0, 0); s.SetOpacity(0.7); s.SetRotation(90); s.SetSize(Stamper.SizeType.e_font_size, 80, -1); s.SetTextAlignment(Stamper.TextAlignment.e_align_center); s.StampText(doc, "Goodbye\nMoon", new PageSet(1, 20, PageSet.Filter.e_even)); doc.Save(output_path + input_filename + ".ex5.pdf", SDFDoc.SaveOptions.e_linearized); } } catch (PDFNetException e) { Console.WriteLine(e.Message); } //-------------------------------------------------------------------------------- // Example 6) Add first page as stamp to all even pages try { using (PDFDoc doc = new PDFDoc(input_path + input_filename + ".pdf")) using (PDFDoc fish_doc = new PDFDoc(input_path + "fish.pdf")) using (Stamper s = new Stamper(Stamper.SizeType.e_relative_scale, .3, .3)) { doc.InitSecurityHandler(); fish_doc.InitSecurityHandler(); s.SetOpacity(1); s.SetRotation(270); s.SetAsBackground(true); s.SetPosition(0.5, 0.5, true); s.SetAlignment(Stamper.HorizontalAlignment.e_horizontal_left, Stamper.VerticalAlignment.e_vertical_bottom); Page page_one = fish_doc.GetPage(1); s.StampPage(doc, page_one, new PageSet(1, doc.GetPageCount(), PageSet.Filter.e_even)); doc.Save(output_path + input_filename + ".ex6.pdf", SDFDoc.SaveOptions.e_linearized); } } catch (PDFNetException e) { Console.WriteLine(e.Message); } //-------------------------------------------------------------------------------- // Example 7) Add image stamp at top right corner in every pages try { using (PDFDoc doc = new PDFDoc(input_path + input_filename + ".pdf")) using (Stamper s = new Stamper(Stamper.SizeType.e_relative_scale, .1, .1)) { doc.InitSecurityHandler(); s.SetOpacity(0.8); s.SetRotation(135); s.SetAsBackground(false); s.ShowsOnPrint(false); s.SetAlignment(Stamper.HorizontalAlignment.e_horizontal_left, Stamper.VerticalAlignment.e_vertical_top); s.SetPosition(10, 10); Image img = Image.Create(doc, input_path + "peppers.jpg"); s.StampImage(doc, img, new PageSet(1, doc.GetPageCount(), PageSet.Filter.e_all)); doc.Save(output_path + input_filename + ".ex7.pdf", SDFDoc.SaveOptions.e_linearized); } } catch (PDFNetException e) { Console.WriteLine(e.Message); } //-------------------------------------------------------------------------------- // Example 8) Add Text stamp to first 2 pages, and image stamp to first page. // Because text stamp is set as background, the image is top of the text // stamp. Text stamp on the first page is not visible. try { using (PDFDoc doc = new PDFDoc(input_path + input_filename + ".pdf")) using (Stamper s = new Stamper(Stamper.SizeType.e_relative_scale, 0.07, -0.1)) { doc.InitSecurityHandler(); s.SetAlignment(Stamper.HorizontalAlignment.e_horizontal_right, Stamper.VerticalAlignment.e_vertical_bottom); s.SetAlignment(Stamper.HorizontalAlignment.e_horizontal_center, Stamper.VerticalAlignment.e_vertical_top); s.SetFont(Font.Create(doc, Font.StandardType1Font.e_courier, true)); s.SetFontColor(new ColorPt(1, 0, 0, 0)); //set color to red s.SetTextAlignment(Stamper.TextAlignment.e_align_right); s.SetAsBackground(true); //set text stamp as background s.StampText(doc, "This is a title!", new PageSet(1, 2)); Image img = Image.Create(doc, input_path + "peppers.jpg"); s.SetAsBackground(false); // set image stamp as foreground s.StampImage(doc, img, new PageSet(1)); doc.Save(output_path + input_filename + ".ex8.pdf", SDFDoc.SaveOptions.e_linearized); } } catch (PDFNetException e) { Console.WriteLine(e.Message); } }
static void Main(string[] args) { PDFNet.Initialize(); // Relative path to the folder containing test files. string input_path = "../../TestFiles/"; string output_path = "../../TestFiles/Output/"; try { using (PDFDoc doc = new PDFDoc()) using (ElementBuilder eb = new ElementBuilder()) // ElementBuilder is used to build new Element objects using (ElementWriter writer = new ElementWriter()) // ElementWriter is used to write Elements to the page { // Start a new page ------------------------------------ // Position an image stream on several places on the page Page page = doc.PageCreate(new Rect(0, 0, 612, 794)); writer.Begin(page); // begin writing to this page // Create an Image that can be reused multiple times in the document or // multiple on the same page. MappedFile img_file = new MappedFile(input_path + "peppers.jpg"); FilterReader img_data = new FilterReader(img_file); Image img = Image.Create(doc, img_data, 400, 600, 8, ColorSpace.CreateDeviceRGB(), Image.InputFilter.e_jpeg); Element element = eb.CreateImage(img, new Matrix2D(200, -145, 20, 300, 200, 150)); writer.WritePlacedElement(element); GState gstate = element.GetGState(); // use the same image (just change its matrix) gstate.SetTransform(200, 0, 0, 300, 50, 450); writer.WritePlacedElement(element); // use the same image again (just change its matrix). writer.WritePlacedElement(eb.CreateImage(img, 300, 600, 200, -150)); writer.End(); // save changes to the current page doc.PagePushBack(page); // Start a new page ------------------------------------ // Construct and draw a path object using different styles page = doc.PageCreate(new Rect(0, 0, 612, 794)); writer.Begin(page); // begin writing to this page eb.Reset(); // Reset GState to default eb.PathBegin(); // start constructing the path eb.MoveTo(306, 396); eb.CurveTo(681, 771, 399.75, 864.75, 306, 771); eb.CurveTo(212.25, 864.75, -69, 771, 306, 396); eb.ClosePath(); element = eb.PathEnd(); // the path is now finished element.SetPathFill(true); // the path should be filled // Set the path color space and color gstate = element.GetGState(); gstate.SetFillColorSpace(ColorSpace.CreateDeviceCMYK()); gstate.SetFillColor(new ColorPt(1, 0, 0, 0)); // cyan gstate.SetTransform(0.5, 0, 0, 0.5, -20, 300); writer.WritePlacedElement(element); // Draw the same path using a different stroke color element.SetPathStroke(true); // this path is should be filled and stroked gstate.SetFillColor(new ColorPt(0, 0, 1, 0)); // yellow gstate.SetStrokeColorSpace(ColorSpace.CreateDeviceRGB()); gstate.SetStrokeColor(new ColorPt(1, 0, 0)); // red gstate.SetTransform(0.5, 0, 0, 0.5, 280, 300); gstate.SetLineWidth(20); writer.WritePlacedElement(element); // Draw the same path with with a given dash pattern element.SetPathFill(false); // this path is should be only stroked gstate.SetStrokeColor(new ColorPt(0, 0, 1)); // blue gstate.SetTransform(0.5, 0, 0, 0.5, 280, 0); double[] dash_pattern = { 30 }; gstate.SetDashPattern(dash_pattern, 0); writer.WritePlacedElement(element); // Use the path as a clipping path writer.WriteElement(eb.CreateGroupBegin()); // Save the graphics state // Start constructing a new path (the old path was lost when we created // a new Element using CreateGroupBegin()). eb.PathBegin(); eb.MoveTo(306, 396); eb.CurveTo(681, 771, 399.75, 864.75, 306, 771); eb.CurveTo(212.25, 864.75, -69, 771, 306, 396); eb.ClosePath(); element = eb.PathEnd(); // path is now built element.SetPathClip(true); // this path is a clipping path element.SetPathStroke(true); // this path is should be filled and stroked gstate = element.GetGState(); gstate.SetTransform(0.5, 0, 0, 0.5, -20, 0); writer.WriteElement(element); writer.WriteElement(eb.CreateImage(img, 100, 300, 400, 600)); writer.WriteElement(eb.CreateGroupEnd()); // Restore the graphics state writer.End(); // save changes to the current page doc.PagePushBack(page); // Start a new page ------------------------------------ page = doc.PageCreate(new Rect(0, 0, 612, 794)); writer.Begin(page); // begin writing to this page eb.Reset(); // Reset GState to default // Begin writing a block of text element = eb.CreateTextBegin(Font.Create(doc, Font.StandardType1Font.e_times_roman), 12); writer.WriteElement(element); string data = "Hello World!"; element = eb.CreateTextRun(data); element.SetTextMatrix(10, 0, 0, 10, 0, 600); element.GetGState().SetLeading(15); // Set the spacing between lines writer.WriteElement(element); writer.WriteElement(eb.CreateTextNewLine()); // New line element = eb.CreateTextRun(data); gstate = element.GetGState(); gstate.SetTextRenderMode(GState.TextRenderingMode.e_stroke_text); gstate.SetCharSpacing(-1.25); gstate.SetWordSpacing(-1.25); writer.WriteElement(element); writer.WriteElement(eb.CreateTextNewLine()); // New line element = eb.CreateTextRun(data); gstate = element.GetGState(); gstate.SetCharSpacing(0); gstate.SetWordSpacing(0); gstate.SetLineWidth(3); gstate.SetTextRenderMode(GState.TextRenderingMode.e_fill_stroke_text); gstate.SetStrokeColorSpace(ColorSpace.CreateDeviceRGB()); gstate.SetStrokeColor(new ColorPt(1, 0, 0)); // red gstate.SetFillColorSpace(ColorSpace.CreateDeviceCMYK()); gstate.SetFillColor(new ColorPt(1, 0, 0, 0)); // cyan writer.WriteElement(element); writer.WriteElement(eb.CreateTextNewLine()); // New line // Set text as a clipping path to the image. element = eb.CreateTextRun(data); gstate = element.GetGState(); gstate.SetTextRenderMode(GState.TextRenderingMode.e_clip_text); writer.WriteElement(element); // Finish the block of text writer.WriteElement(eb.CreateTextEnd()); // Draw an image that will be clipped by the above text writer.WriteElement(eb.CreateImage(img, 10, 100, 1300, 720)); writer.End(); // save changes to the current page doc.PagePushBack(page); // Start a new page ------------------------------------ // // The example illustrates how to embed the external font in a PDF document. // The example also shows how ElementReader can be used to copy and modify // Elements between pages. using (ElementReader reader = new ElementReader()) { // Start reading Elements from the last page. We will copy all Elements to // a new page but will modify the font associated with text. reader.Begin(doc.GetPage(doc.GetPageCount())); page = doc.PageCreate(new Rect(0, 0, 1300, 794)); writer.Begin(page); // begin writing to this page eb.Reset(); // Reset GState to default // Embed an external font in the document. Font font = Font.CreateTrueTypeFont(doc, input_path + "font.ttf"); while ((element = reader.Next()) != null) // Read page contents { if (element.GetType() == Element.Type.e_text) { element.GetGState().SetFont(font, 12); } writer.WriteElement(element); } reader.End(); writer.End(); // save changes to the current page doc.PagePushBack(page); // Start a new page ------------------------------------ // // The example illustrates how to embed the external font in a PDF document. // The example also shows how ElementReader can be used to copy and modify // Elements between pages. // Start reading Elements from the last page. We will copy all Elements to // a new page but will modify the font associated with text. reader.Begin(doc.GetPage(doc.GetPageCount())); page = doc.PageCreate(new Rect(0, 0, 1300, 794)); writer.Begin(page); // begin writing to this page eb.Reset(); // Reset GState to default // Embed an external font in the document. Font font2 = Font.CreateType1Font(doc, input_path + "Misc-Fixed.pfa"); while ((element = reader.Next()) != null) // Read page contents { if (element.GetType() == Element.Type.e_text) { element.GetGState().SetFont(font2, 12); } writer.WriteElement(element); } reader.End(); writer.End(); // save changes to the current page doc.PagePushBack(page); // Start a new page ------------------------------------ page = doc.PageCreate(); writer.Begin(page); // begin writing to this page eb.Reset(); // Reset GState to default // Begin writing a block of text element = eb.CreateTextBegin(Font.Create(doc, Font.StandardType1Font.e_times_roman), 12); element.SetTextMatrix(1.5, 0, 0, 1.5, 50, 600); element.GetGState().SetLeading(15); // Set the spacing between lines writer.WriteElement(element); string para = "A PDF text object consists of operators that can show " + "text strings, move the text position, and set text state and certain " + "other parameters. In addition, there are three parameters that are " + "defined only within a text object and do not persist from one text " + "object to the next: Tm, the text matrix, Tlm, the text line matrix, " + "Trm, the text rendering matrix, actually just an intermediate result " + "that combines the effects of text state parameters, the text matrix " + "(Tm), and the current transformation matrix"; int para_end = para.Length; int text_run = 0; int text_run_end; double para_width = 300; // paragraph width is 300 units double cur_width = 0; while (text_run < para_end) { text_run_end = para.IndexOf(' ', text_run); if (text_run_end < 0) { text_run_end = para_end - 1; } string text = para.Substring(text_run, text_run_end - text_run + 1); element = eb.CreateTextRun(text); if (cur_width + element.GetTextLength() < para_width) { writer.WriteElement(element); cur_width += element.GetTextLength(); } else { writer.WriteElement(eb.CreateTextNewLine()); // New line text = para.Substring(text_run, text_run_end - text_run + 1); element = eb.CreateTextRun(text); cur_width = element.GetTextLength(); writer.WriteElement(element); } text_run = text_run_end + 1; } // ----------------------------------------------------------------------- // The following code snippet illustrates how to adjust spacing between // characters (text runs). element = eb.CreateTextNewLine(); writer.WriteElement(element); // Skip 2 lines writer.WriteElement(element); writer.WriteElement(eb.CreateTextRun("An example of space adjustments between inter-characters:")); writer.WriteElement(eb.CreateTextNewLine()); // Write string "AWAY" without space adjustments between characters. element = eb.CreateTextRun("AWAY"); writer.WriteElement(element); writer.WriteElement(eb.CreateTextNewLine()); // Write string "AWAY" with space adjustments between characters. element = eb.CreateTextRun("A"); writer.WriteElement(element); element = eb.CreateTextRun("W"); element.SetPosAdjustment(140); writer.WriteElement(element); element = eb.CreateTextRun("A"); element.SetPosAdjustment(140); writer.WriteElement(element); element = eb.CreateTextRun("Y again"); element.SetPosAdjustment(115); writer.WriteElement(element); // Draw the same strings using direct content output... writer.Flush(); // flush pending Element writing operations. // You can also write page content directly to the content stream using // ElementWriter.WriteString(...) and ElementWriter.WriteBuffer(...) methods. // Note that if you are planning to use these functions you need to be familiar // with PDF page content operators (see Appendix A in PDF Reference Manual). // Because it is easy to make mistakes during direct output we recommend that // you use ElementBuilder and Element interface instead. writer.WriteString("T* T* "); // New Lines // writer.WriteElement(eb.CreateTextNewLine()); writer.WriteString("(Direct output to PDF page content stream:) Tj T* "); writer.WriteString("(AWAY) Tj T* "); writer.WriteString("[(A)140(W)140(A)115(Y again)] TJ "); // Finish the block of text writer.WriteElement(eb.CreateTextEnd()); writer.End(); // save changes to the current page doc.PagePushBack(page); // Start a new page ------------------------------------ // Image Masks // // In the opaque imaging model, images mark all areas they occupy on the page as // if with opaque paint. All portions of the image, whether black, white, gray, // or color, completely obscure any marks that may previously have existed in the // same place on the page. // In the graphic arts industry and page layout applications, however, it is common // to crop or 'mask out' the background of an image and then place the masked image // on a different background, allowing the existing background to show through the // masked areas. This sample illustrates how to use image masks. page = doc.PageCreate(); writer.Begin(page); // begin writing to the page // Create the Image Mask MappedFile imgf = new MappedFile(input_path + "imagemask.dat"); FilterReader mask_read = new FilterReader(imgf); ColorSpace device_gray = ColorSpace.CreateDeviceGray(); Image mask = Image.Create(doc, mask_read, 64, 64, 1, device_gray, Image.InputFilter.e_ascii_hex); mask.GetSDFObj().PutBool("ImageMask", true); element = eb.CreateRect(0, 0, 612, 794); element.SetPathStroke(false); element.SetPathFill(true); element.GetGState().SetFillColorSpace(device_gray); element.GetGState().SetFillColor(new ColorPt(0.8)); writer.WritePlacedElement(element); element = eb.CreateImage(mask, new Matrix2D(200, 0, 0, -200, 40, 680)); element.GetGState().SetFillColor(new ColorPt(0.1)); writer.WritePlacedElement(element); element.GetGState().SetFillColorSpace(ColorSpace.CreateDeviceRGB()); element.GetGState().SetFillColor(new ColorPt(1, 0, 0)); element = eb.CreateImage(mask, new Matrix2D(200, 0, 0, -200, 320, 680)); writer.WritePlacedElement(element); element.GetGState().SetFillColor(new ColorPt(0, 1, 0)); element = eb.CreateImage(mask, new Matrix2D(200, 0, 0, -200, 40, 380)); writer.WritePlacedElement(element); { // This sample illustrates Explicit Masking. img = Image.Create(doc, input_path + "peppers.jpg"); // mask is the explicit mask for the primary (base) image img.SetMask(mask); element = eb.CreateImage(img, new Matrix2D(200, 0, 0, -200, 320, 380)); writer.WritePlacedElement(element); } writer.End(); // save changes to the current page doc.PagePushBack(page); // Transparency sample ---------------------------------- // Start a new page ------------------------------------- page = doc.PageCreate(); writer.Begin(page); // begin writing to this page eb.Reset(); // Reset the GState to default // Write some transparent text at the bottom of the page. element = eb.CreateTextBegin(Font.Create(doc, Font.StandardType1Font.e_times_roman), 100); // Set the text knockout attribute. Text knockout must be set outside of // the text group. gstate = element.GetGState(); gstate.SetTextKnockout(false); gstate.SetBlendMode(GState.BlendMode.e_bl_difference); writer.WriteElement(element); element = eb.CreateTextRun("Transparency"); element.SetTextMatrix(1, 0, 0, 1, 30, 30); gstate = element.GetGState(); gstate.SetFillColorSpace(ColorSpace.CreateDeviceCMYK()); gstate.SetFillColor(new ColorPt(1, 0, 0, 0)); gstate.SetFillOpacity(0.5); writer.WriteElement(element); // Write the same text on top the old; shifted by 3 points element.SetTextMatrix(1, 0, 0, 1, 33, 33); gstate.SetFillColor(new ColorPt(0, 1, 0, 0)); gstate.SetFillOpacity(0.5); writer.WriteElement(element); writer.WriteElement(eb.CreateTextEnd()); // Draw three overlapping transparent circles. eb.PathBegin(); // start constructing the path eb.MoveTo(459.223, 505.646); eb.CurveTo(459.223, 415.841, 389.85, 343.04, 304.273, 343.04); eb.CurveTo(218.697, 343.04, 149.324, 415.841, 149.324, 505.646); eb.CurveTo(149.324, 595.45, 218.697, 668.25, 304.273, 668.25); eb.CurveTo(389.85, 668.25, 459.223, 595.45, 459.223, 505.646); element = eb.PathEnd(); element.SetPathFill(true); gstate = element.GetGState(); gstate.SetFillColorSpace(ColorSpace.CreateDeviceRGB()); gstate.SetFillColor(new ColorPt(0, 0, 1)); // Blue Circle gstate.SetBlendMode(GState.BlendMode.e_bl_normal); gstate.SetFillOpacity(0.5); writer.WriteElement(element); // Translate relative to the Blue Circle gstate.SetTransform(1, 0, 0, 1, 113, -185); gstate.SetFillColor(new ColorPt(0, 1, 0)); // Green Circle gstate.SetFillOpacity(0.5); writer.WriteElement(element); // Translate relative to the Green Circle gstate.SetTransform(1, 0, 0, 1, -220, 0); gstate.SetFillColor(new ColorPt(1, 0, 0)); // Red Circle gstate.SetFillOpacity(0.5); writer.WriteElement(element); writer.End(); // save changes to the current page doc.PagePushBack(page); // End page ------------------------------------ } doc.Save(output_path + "element_builder.pdf", SDFDoc.SaveOptions.e_remove_unused); Console.WriteLine("Done. Result saved in element_builder.pdf..."); } } catch (PDFNetException e) { Console.WriteLine(e.Message); } }
private static void GrepDates(String pdf_file) { Console.WriteLine("Search dates in " + pdf_file); string text_name = pdf_file.Replace(".pdf", ".txt"); string input_file = pdf_file; ErrorCode error_code = Library.Initialize(sn, key); if (error_code != ErrorCode.e_ErrSuccess) { Console.WriteLine("Library Initialize Error: {0}", error_code); return; } var text = ""; try { using (var doc = new PDFDoc(input_file)) { error_code = doc.Load(null); if (error_code != ErrorCode.e_ErrSuccess) { Console.WriteLine("The PDFDoc " + input_file + " Error: " + error_code); return; } using (var writer = new StreamWriter(text_name, false, System.Text.Encoding.Unicode)) { int pageCount = doc.GetPageCount(); for (int i = 0; i < pageCount; i++) { using (var page = doc.GetPage(i)) { page.StartParse((int)PDFPage.ParseFlags.e_ParsePageNormal, null, false); // Get the text select object. using (var text_select = new TextPage(page, (int)TextPage.TextParseFlags.e_ParseTextNormal)) { int count = text_select.GetCharCount(); if (count > 0) { String chars = text_select.GetChars(0, count); text = text + chars; } } } } foreach (var dateTime in GetDates(text)) { writer.WriteLine(dateTime.Date.ToString("yyyy-MM-dd")); } } } } catch (System.Exception e) { Console.WriteLine(e.Message); } Library.Release(); }
public FileItemDTO CombineFiles(List <FileItemEntity> fileItems) { try { using (PDFDoc doc = new PDFDoc()) { doc.InitSecurityHandler(); var fileNewName = new StringBuilder(); foreach (var fileItem in fileItems) { if (fileNewName.Length > 0) { fileNewName.Append("_"); } fileNewName.Append(fileItem.FileName.TrimEnd(".pdf".ToCharArray())); fileItem.FileFullPath = FileUtils.GetDefaultInputPath() + fileItem.FileName; File.WriteAllBytes(fileItem.FileFullPath, fileItem.Bytes); using (PDFDoc in_doc = new PDFDoc(fileItem.FileFullPath)) { in_doc.InitSecurityHandler(); doc.InsertPages(doc.GetPageCount() + 1, in_doc, 1, in_doc.GetPageCount(), PDFDoc.InsertFlag.e_none); } } #region Teste //Era pra funcionar, mas lança uma exceção no método "new_doc.ImportPages" //ArrayList copy_pages = new ArrayList(); //for (PageIterator itr = in_doc.GetPageIterator(); itr.HasNext(); itr.Next()) //{ // copy_pages.Add(itr.Current()); //} //var imported_pages = new_doc.ImportPages(copy_pages, false); //for (int i = 0; i != imported_pages.Count; ++i) //{ // new_doc.PagePushBack((Page)imported_pages[i]); //} #endregion var fileItemDTO = new FileItemDTO() { Id = new Random().Next(1, 100), FileFullPath = FileUtils.GetNewFileName(fileNewName.ToString(), FileNameOptionEnum.Combine) }; fileItemDTO.FileName = FileUtils.GetSafeFileName(fileItemDTO.FileFullPath); doc.Save(fileItemDTO.FileFullPath, SDFDoc.SaveOptions.e_linearized); return(fileItemDTO); } } catch (PDFNetException ex) { throw; } catch (Exception ex) { throw; } }