public FileItemDTO ConvertFileToPDF(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.Convert)
            };

            fileItemDTO.FileName = FileUtils.GetSafeFileName(fileItemDTO.FileFullPath);

            using (PDFDoc doc = new PDFDoc())
            {
                try
                {
                    switch (FileUtils.GetFileType(fileItem.FileFullPath))
                    {
                    case FileType.MSOffice:
                        pdftron.PDF.Convert.OfficeToPDF(doc, fileItem.FileFullPath, null);
                        break;

                    case FileType.HTML:
                        HTML2PDF converter = new HTML2PDF();

                        var htmlString = File.ReadAllText(fileItem.FileFullPath);

                        converter.InsertFromHtmlString(htmlString);

                        converter.Convert(doc);
                        break;

                    case FileType.Other:
                        pdftron.PDF.Convert.ToPdf(doc, fileItem.FileFullPath);
                        break;

                    case FileType.NotMapped:
                        throw new ArgumentException($"Extensão {FileUtils.GetFileExtension(fileItem.FileFullPath)} não mapeada");

                    default:
                        break;
                    }

                    doc.Save(fileItemDTO.FileFullPath, SDFDoc.SaveOptions.e_linearized);

                    return(fileItemDTO);
                }
                catch (PDFNetException ex)
                {
                    throw;
                }
                catch (Exception ex)
                {
                    throw;
                }
            }
        }
        //// 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 Redact(string input, string output, ArrayList rarr, Redactor.Appearance app)
 {
     using (PDFDoc doc = new PDFDoc(input))
     {
         doc.InitSecurityHandler();
         Redactor.Redact(doc, rarr, app, false, true);
         doc.Save(output, SDFDoc.SaveOptions.e_linearized);
     }
 }
Exemple #4
0
        static void Main(string[] args)
        {
            PDFNet.Initialize();

            // Create a PDF Package.
            try
            {
                using (PDFDoc doc = new PDFDoc())
                {
                    AddPackage(doc, input_path + "numbered.pdf", "My File 1");
                    AddPackage(doc, input_path + "newsletter.pdf", "My Newsletter...");
                    AddPackage(doc, input_path + "peppers.jpg", "An image");
                    AddCovePage(doc);
                    doc.Save(output_path + "package.pdf", SDFDoc.SaveOptions.e_linearized);
                    Console.WriteLine("Done.");
                }
            }
            catch (PDFNetException e)
            {
                Console.WriteLine(e.Message);
            }

            // Extract parts from a PDF Package.
            try
            {
                using (PDFDoc doc = new PDFDoc(output_path + "package.pdf"))
                {
                    doc.InitSecurityHandler();

                    pdftron.SDF.NameTree files = NameTree.Find(doc, "EmbeddedFiles");
                    if (files.IsValid())
                    {
                        // Traverse the list of embedded files.
                        NameTreeIterator i = files.GetIterator();
                        for (int counter = 0; i.HasNext(); i.Next(), ++counter)
                        {
                            string entry_name = i.Key().GetAsPDFText();
                            Console.WriteLine("Part: {0}", entry_name);
                            FileSpec file_spec = new FileSpec(i.Value());
                            Filter   stm       = file_spec.GetFileData();
                            if (stm != null)
                            {
                                string fname = output_path + "extract_" + counter.ToString() + ".pdf";
                                stm.WriteToFile(fname, false);
                            }
                        }
                    }
                }

                Console.WriteLine("Done.");
            }
            catch (PDFNetException e)
            {
                Console.WriteLine(e.Message);
            }
        }
        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);
            }
        }
        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);
                }
            }
        }
Exemple #7
0
        public string BookMark(List <TablePos> tablePoses)
        {
            ClearBookMarks(pdfDoc);
            tablePoses.ForEach(tablePos =>
                               CreateTablePosHighlight(tablePos, pdfDoc));
            string path             = System.IO.Path.GetDirectoryName(_pdfFile);
            var    name             = System.IO.Path.GetFileNameWithoutExtension(_pdfFile);
            string BookmarkFilePath = System.IO.Path.Combine(path, name + "_bookmark.pdf");

            pdfDoc.Save(BookmarkFilePath, 0);
            return(BookmarkFilePath);
        }
        public static Stream ConvertToPDF(Stream stream)
        {
            using var filter = ConvertStreamToFilter(stream);

            using var pdfDoc = new PDFDoc();

            Convert.OfficeToPDF(pdfDoc, filter, null);

            var memoryStream = new MemoryStream();

            pdfDoc.Save(memoryStream, SDFDoc.SaveOptions.e_linearized);

            return(memoryStream);
        }
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                using (PDFDoc doc = new PDFDoc())
                {
                    doc.InitSecurityHandler();

                    pdftron.PDF.Page newPg = doc.PageCreate();
                    doc.PagePushBack(newPg);

                    Ink ink = Ink.Create(doc, new pdftron.PDF.Rect(110, 10, 300, 200));
                    pdftron.PDF.Point pt3 = new pdftron.PDF.Point(110, 10);
                    //pt3.x = 110; pt3.y = 10;
                    ink.SetPoint(0, 0, pt3);
                    pt3.x = 150; pt3.y = 50;
                    ink.SetPoint(0, 1, pt3);
                    pt3.x = 190; pt3.y = 60;
                    ink.SetPoint(0, 2, pt3);
                    pt3.x = 180; pt3.y = 90;
                    ink.SetPoint(1, 0, pt3);
                    pt3.x = 190; pt3.y = 95;
                    ink.SetPoint(1, 1, pt3);
                    pt3.x = 200; pt3.y = 100;
                    ink.SetPoint(1, 2, pt3);
                    pt3.x = 166; pt3.y = 86;
                    ink.SetPoint(2, 0, pt3);
                    pt3.x = 196; pt3.y = 96;
                    ink.SetPoint(2, 1, pt3);
                    pt3.x = 221; pt3.y = 121;
                    ink.SetPoint(2, 2, pt3);
                    pt3.x = 288; pt3.y = 188;
                    ink.SetPoint(2, 3, pt3);
                    ink.SetColor(new ColorPt(0, 1, 1), 3);
                    newPg.AnnotPushBack(ink);

                    // Save as a linearized file which is most popular
                    // and effective format for quick PDF Viewing.
                    doc.Save("linearized_output.pdf", SDFDoc.SaveOptions.e_linearized);

                    System.Console.WriteLine("Done. Results saved in linearized_output.pdf");

                    MessageBox.Show("Done. Results saved in linearized_output.pdf", "Document Creation");
                }
            }
            catch (PDFNetException ex)
            {
                System.Console.WriteLine(ex.Message);
            }
        }
        static void SimpleConvert(String input_filename, String output_filename)
        {
            // Start with a PDFDoc (the conversion destination)
            using (PDFDoc pdfdoc = new PDFDoc())
            {
                // perform the conversion with no optional parameters
                pdftron.PDF.Convert.OfficeToPDF(pdfdoc, input_path + input_filename, null);

                // save the result
                pdfdoc.Save(output_path + output_filename, SDFDoc.SaveOptions.e_linearized);

                // And we're done!
                Console.WriteLine("Saved " + output_filename);
            }
        }
        public void ExportPdf()
        {
            using PDFDoc pdfdoc = new PDFDoc();
            Convert.OfficeToPDF(pdfdoc, $"{ReportTemplate.TemplatePath}{ReportTemplate.ReceiptTemplate}.docx", null);
            Page            pg       = pdfdoc.GetPage(1);
            ContentReplacer replacer = new ContentReplacer();

            SetData();
            foreach (string key in Dic.Keys)
            {
                replacer.AddString(key, Dic[key]);
            }
            replacer.Process(pg);
            pdfdoc.Save($"{ReportTemplate.TemplateOutputPath}{ReportTemplate.ReceiptTemplate}{ReportTemplate.Resx}.pdf", SDFDoc.SaveOptions.e_linearized);
        }
        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);
                    }
                }
            }
        }
        public FileStreamWithPdftron(string pdfFilePath, FileItemStreamType streamType, WaterMarkInfo watermarkInfo)
        {
            var tempFilePath = string.Empty;

            try
            {
                tempFilePath = Path.GetTempFileName();

                pdftron.PDFNet.Initialize(Properties.Settings.Default.PDFTronLicense);

                using (var doc = new PDFDoc(pdfFilePath))
                {
                    if (null != watermarkInfo)
                    {
                        WatermarkFile(doc, watermarkInfo);
                    }

                    if (streamType == FileItemStreamType.Downloadable)
                    {
                        doc.Save(tempFilePath, SDFDoc.SaveOptions.e_compatibility);
                    }
                    else
                    {
                        Convert.ToXod(doc, tempFilePath);
                    }

                    doc.Close();
                }

                _wrappedStream = new FileStreamWithDelete(tempFilePath, FileMode.Open);
            }
            catch
            {
                if (File.Exists(tempFilePath))
                {
                    File.Delete(tempFilePath);
                }
                throw;
            }
            finally
            {
                if (File.Exists(pdfFilePath))
                {
                    File.Delete(pdfFilePath);
                }
            }
        }
        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 SignPDF()
        {
            PDFNet.Initialize();
            // Create a page
            using (var doc = new PDFDoc()) {
                var page = doc.PageCreate(new Rect(0, 0, 595, 842));
                page.SetRotation(Page.Rotate.e_0);
                page.SetCropBox(new Rect(0, 0, 595, 842));
                doc.PagePushBack(page);

                var rect    = new Rect(0, 0, 0, 0);
                var fieldId = Guid.NewGuid().ToString();

                var fieldToSign         = doc.FieldCreate(fieldId, Field.Type.e_signature);
                var signatureAnnotation = Widget.Create(doc, rect, fieldToSign);

                signatureAnnotation.SetFlag(Annot.Flag.e_print, true);
                signatureAnnotation.SetPage(page);
                var widgetObj = signatureAnnotation.GetSDFObj();
                widgetObj.PutNumber("F", 132.0);
                widgetObj.PutName("Type", "Annot");

                page.AnnotPushBack(signatureAnnotation);

                //Create the signature handler
                var sigHandler = new RemoteSignatureTimeStampPdfHandler(new HttpClient());

                //Add handler to PDFDoc instance
                var sigHandlerId = doc.AddSignatureHandler(sigHandler);

                // Add the SignatureHandler instance to PDFDoc, making sure to keep track of it using the ID returned.
                var sigDict = fieldToSign.UseSignatureHandler(sigHandlerId);

                var signatureObject = signatureAnnotation.GetSDFObj();

                var cultureInfo = new CultureInfo("en-US");
                var gmt1Date    = DateTime.Now;

                var value = gmt1Date.ToString("'D:'yyyyMMddHHmmsszzz", cultureInfo);

                // Add signing date
                sigDict.PutString("M", value);

                doc.Save(SDFDoc.SaveOptions.e_incremental);
            }
        }
        static void FlexibleConvert(String input_filename, String output_filename)
        {
            // Start with a PDFDoc (the conversion destination)
            using (PDFDoc pdfdoc = new PDFDoc())
            {
                OfficeToPDFOptions options = new OfficeToPDFOptions();
                options.SetSmartSubstitutionPluginPath(input_path);
                // create a conversion object -- this sets things up but does not yet
                // perform any conversion logic.
                // in a multithreaded environment, this object can be used to monitor
                // the conversion progress and potentially cancel it as well
                DocumentConversion conversion = pdftron.PDF.Convert.StreamingPDFConversion(
                    pdfdoc, input_path + input_filename, options);

                // actually perform the conversion
                // this particular method will not throw on conversion failure, but will
                // return an error status instead
                if (conversion.TryConvert() == DocumentConversionResult.e_document_conversion_success)
                {
                    int num_warnings = conversion.GetNumWarnings();

                    // print information about the conversion
                    for (int i = 0; i < num_warnings; ++i)
                    {
                        Console.WriteLine("Warning: " + conversion.GetWarningString(i));
                    }

                    // save the result
                    pdfdoc.Save(output_path + output_filename, SDFDoc.SaveOptions.e_linearized);
                    // done
                    Console.WriteLine("Saved " + output_filename);
                }
                else
                {
                    Console.WriteLine("Encountered an error during conversion: " + conversion.GetErrorString());
                }
            }
        }
Exemple #17
0
        static void Main(string[] args)
        {
            PDFNet.Initialize();

            try
            {
                using (PDFDoc doc = new PDFDoc())
                {
                    Page page = doc.PageCreate();
                    doc.PagePushBack(page);
                    Obj annots = doc.CreateIndirectArray();
                    page.GetSDFObj().Put("Annots", annots);

                    Create3DAnnotation(doc, annots);
                    doc.Save(output_path + "dice_u3d.pdf", SDFDoc.SaveOptions.e_linearized);
                }
                Console.WriteLine("Done");
            }
            catch (PDFNetException e)
            {
                Console.WriteLine(e.Message);
            }
        }
        // POST: api/Annotations
        public void Post([FromBody]Annotations value)
        {
            DocumentRepository documentData = new DocumentRepository();
            CurrentDocuments currentDocuments = documentData.GetCurrentDocumentPathPDF(Utility.GetUserName());
            string [] pathParts = currentDocuments.PathToCurrentPDFDocument.Split('\\');
            string tempPDFPath = string.Empty;

            for (int i = 0; i < pathParts.Length - 1 ; i++)
            {
                tempPDFPath = tempPDFPath + pathParts[i] + "\\";
            }

            tempPDFPath = tempPDFPath + "temp" + pathParts[pathParts.Length -1];

            System.IO.File.Copy(currentDocuments.PathToCurrentPDFDocument, tempPDFPath,true);
            try
            {

                PDFDoc in_doc = new PDFDoc(tempPDFPath);
                {
                    in_doc.InitSecurityHandler();

                    //string str = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?><xfdf xmlns=\"http://ns.adobe.com/xfdf\" xml:space=\"preserve\"><square subject=\"Rectangle\" page=\"0\" name=\"cf4d2e58-e9c5-2a58-5b4d-9b4b1a330e45\" title=\"user\" creationdate=\"D:20120827112326-07'00'\" date=\"D:20120827112326-07'00'\" rect=\"227.7814207650273,597.6174863387978,437.07103825136608,705.0491803278688\" color=\"#000000\" interior-color=\"#FFFF00\" flags=\"print\" width=\"1\"><popup flags=\"print,nozoom,norotate\" open=\"no\" page=\"0\" rect=\"0,792,0,792\" /></square></xfdf>";
                    string str = value.Data;

                    using (FDFDoc fdoc = new FDFDoc(FDFDoc.CreateFromXFDF(str)))
                    {
                        in_doc.FDFMerge(fdoc);
                        in_doc.Save(currentDocuments.PathToCurrentPDFDocument, SDFDoc.SaveOptions.e_linearized);
                    }
                }
            }
            catch (PDFNetException e)
            {
                Console.WriteLine(e.Message);
            }
        }
        // POST: api/Annotations
        public void Post([FromBody]Annotations value)
        {
            DocumentRepository documentData = new DocumentRepository();
            CurrentDocuments currentDocuments = documentData.GetCurrentDocumentPathPdf(Utility.GetUserName());
            string [] pathParts = currentDocuments.PathToCurrentPdfDocument.Split('\\');
            string tempPdfPath = string.Empty;

            for (int i = 0; i < pathParts.Length - 1 ; i++)
            {
                tempPdfPath = tempPdfPath + pathParts[i] + "\\";
            }

            tempPdfPath = tempPdfPath + "temp" + pathParts[pathParts.Length -1];

            System.IO.File.Copy(currentDocuments.PathToCurrentPdfDocument, tempPdfPath,true);
            try
            {
                PDFDoc inDoc = new PDFDoc(tempPdfPath);
                {
                   inDoc.InitSecurityHandler();

                    string str = value.Data;

                    using (FDFDoc fdoc = new FDFDoc(FDFDoc.CreateFromXFDF(str)))
                    {
                        inDoc.FDFMerge(fdoc);
                        inDoc.FlattenAnnotations();
                        inDoc.Save(currentDocuments.PathToCurrentPdfDocument, SDFDoc.SaveOptions.e_incremental);
                        //inDoc.Save(currentDocuments.PathToCurrentPdfDocument, SDFDoc.SaveOptions.e_linearized);
                    }
                }
            }
            catch (PDFNetException e)
            {
                Console.WriteLine(e.Message);
            }
        }
        /// <summary>
        //-----------------------------------------------------------------------------------
        // This sample illustrates how to embed various raster image formats
        // (e.g. TIFF, JPEG, JPEG2000, JBIG2, GIF, PNG, BMP, etc.) in a PDF document.
        //-----------------------------------------------------------------------------------
        /// </summary>
        static void Main(string[] args)
        {
            PDFNet.Initialize();

            // Relative path to the folder containing test files.
            string input_path  = "../../TestFiles/";
            string output_path = "../../TestFiles/Output/";

            try
            {
                using (PDFDoc doc = new PDFDoc())
                    using (ElementBuilder bld = new ElementBuilder())      // Used to build new Element objects
                        using (ElementWriter writer = new ElementWriter()) // Used to write Elements to the page
                        {
                            Page page = doc.PageCreate();                  // Start a new page
                            writer.Begin(page);                            // Begin writing to this page

                            // ----------------------------------------------------------
                            // Embed a JPEG image to the output document.
                            Image img = Image.Create(doc, input_path + "peppers.jpg");

                            // You can also directly add any .NET Bitmap. The following commented-out code
                            // is equivalent to the above line:
                            //    System.Drawing.Bitmap bmp;
                            //    System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(input_path + "peppers.jpg");
                            //    Image img = Image.Create(doc, bmp);

                            Element element = bld.CreateImage(img, 50, 500, img.GetImageWidth() / 2, img.GetImageHeight() / 2);
                            writer.WritePlacedElement(element);

                            // ----------------------------------------------------------
                            // Add a PNG image to the output file
                            img     = Image.Create(doc, input_path + "butterfly.png");
                            element = bld.CreateImage(img, new Matrix2D(100, 0, 0, 100, 300, 500));
                            writer.WritePlacedElement(element);

                            // ----------------------------------------------------------
                            // Add a GIF image to the output file
                            img     = Image.Create(doc, input_path + "pdfnet.gif");
                            element = bld.CreateImage(img, new Matrix2D(img.GetImageWidth(), 0, 0, img.GetImageHeight(), 50, 350));
                            writer.WritePlacedElement(element);

                            // ----------------------------------------------------------
                            // Add a TIFF image to the output file
                            img     = Image.Create(doc, input_path + "grayscale.tif");
                            element = bld.CreateImage(img, new Matrix2D(img.GetImageWidth(), 0, 0, img.GetImageHeight(), 10, 50));
                            writer.WritePlacedElement(element);

                            writer.End();           // Save the page
                            doc.PagePushBack(page); // Add the page to the document page sequence

                            // ----------------------------------------------------------
                            // Add a BMP image to the output file

                            /*
                             * bmp = new System.Drawing.Bitmap(input_path + "pdftron.bmp");
                             *                  img = Image.Create(doc, bmp);
                             *                  element = bld.CreateImage(img, new Matrix2D(bmp.Width, 0, 0, bmp.Height, 255, 700));
                             *                  writer.WritePlacedElement(element);
                             *
                             *                  writer.End();	// Finish writing to the page
                             *                  doc.PagePushBack(page);
                             */

                            // ----------------------------------------------------------
                            // Embed a monochrome TIFF. Compress the image using lossy JBIG2 filter.

                            page = doc.PageCreate(new pdftron.PDF.Rect(0, 0, 612, 794));
                            writer.Begin(page); // begin writing to this page

                            // Note: encoder hints can be used to select between different compression methods.
                            // For example to instruct PDFNet to compress a monochrome image using JBIG2 compression.
                            ObjSet hint_set = new ObjSet();
                            Obj    enc      = hint_set.CreateArray(); // Initialize encoder 'hint' parameter
                            enc.PushBackName("JBIG2");
                            enc.PushBackName("Lossy");

                            img     = pdftron.PDF.Image.Create(doc, input_path + "multipage.tif", enc);
                            element = bld.CreateImage(img, new Matrix2D(612, 0, 0, 794, 0, 0));
                            writer.WritePlacedElement(element);

                            writer.End();           // Save the page
                            doc.PagePushBack(page); // Add the page to the document page sequence

                            // ----------------------------------------------------------
                            // Add a JPEG2000 (JP2) image to the output file

                            // Create a new page
                            page = doc.PageCreate();
                            writer.Begin(page); // Begin writing to the page

                            // Embed the image.
                            img = pdftron.PDF.Image.Create(doc, input_path + "palm.jp2");

                            // Position the image on the page.
                            element = bld.CreateImage(img, new Matrix2D(img.GetImageWidth(), 0, 0, img.GetImageHeight(), 96, 80));
                            writer.WritePlacedElement(element);

                            // Write 'JPEG2000 Sample' text string under the image.
                            writer.WriteElement(bld.CreateTextBegin(pdftron.PDF.Font.Create(doc, pdftron.PDF.Font.StandardType1Font.e_times_roman), 32));
                            element = bld.CreateTextRun("JPEG2000 Sample");
                            element.SetTextMatrix(1, 0, 0, 1, 190, 30);
                            writer.WriteElement(element);
                            writer.WriteElement(bld.CreateTextEnd());

                            writer.End(); // Finish writing to the page
                            doc.PagePushBack(page);


                            doc.Save(output_path + "addimage.pdf", SDFDoc.SaveOptions.e_linearized);
                            Console.WriteLine("Done. Result saved in addimage.pdf...");
                        }
            }
            catch (PDFNetException e)
            {
                Console.WriteLine(e.Message);
            }
        }
        // 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;
            }
        }
        static Boolean ConvertToPdfFromFile()
        {
            System.Collections.ArrayList testfiles = new System.Collections.ArrayList();
            testfiles.Add(new ConvertTestCS.Testfile("simple-powerpoint_2007.pptx", "pptx2pdf.pdf"));
            testfiles.Add(new ConvertTestCS.Testfile("simple-text.txt", "txt2pdf.pdf"));
            testfiles.Add(new ConvertTestCS.Testfile("simple-word_2007.docx", "docx2pdf.pdf"));
            testfiles.Add(new ConvertTestCS.Testfile("simple-rtf.rtf", "rtf2pdf.pdf"));
            testfiles.Add(new ConvertTestCS.Testfile("simple-excel_2007.xlsx", "xlsx2pdf.pdf"));
            testfiles.Add(new ConvertTestCS.Testfile("simple-publisher.pub", "pub2pdf.pdf"));
            testfiles.Add(new ConvertTestCS.Testfile("butterfly.png", "png2pdf.pdf"));
            testfiles.Add(new ConvertTestCS.Testfile("simple-emf.emf", "emf2pdf.pdf"));
            testfiles.Add(new ConvertTestCS.Testfile("simple-xps.xps", "xps2pdf.pdf"));
            // testfiles.Add(new ConvertTestCS.Testfile("simple-webpage.mht", "mht2pdf.pdf"));
            testfiles.Add(new ConvertTestCS.Testfile("simple-webpage.html", "html2pdf.pdf"));

            Boolean err = false;
            Boolean uninstallPrinterWhenDone = false;

            if (pdftron.PDF.Convert.Printer.IsInstalled("PDFTron Creator"))
            {
                pdftron.PDF.Convert.Printer.SetPrinterName("PDFTron Creator");
            }
            else if (!pdftron.PDF.Convert.Printer.IsInstalled())
            {
                try
                {
                    Console.WriteLine("Installing printer (requires administrator)");
                    pdftron.PDF.Convert.Printer.Install();
                    Console.WriteLine("Installed printer " + pdftron.PDF.Convert.Printer.GetPrinterName());
                    // the function ConvertToXpsFromFile may require the printer so leave it installed
                    // uninstallPrinterWhenDone = true;
                }
                catch (PDFNetException e)
                {
                    Console.WriteLine("ERROR: Unable to install printer.");
                    Console.WriteLine(e.Message);
                    err = true;
                }
                catch
                {
                    Console.WriteLine("ERROR: Unable to install printer. Make sure that the package's bitness matches your operating system's bitness and that you are running with administrator privileges.");
                }
            }

            foreach (Testfile file in testfiles)
            {
                try
                {
                    using (pdftron.PDF.PDFDoc pdfdoc = new PDFDoc())
                    {
                        if (pdftron.PDF.Convert.RequiresPrinter(inputPath + file.inputFile))
                        {
                            Console.WriteLine("Printing file: " + file.inputFile);
                        }
                        pdftron.PDF.Convert.ToPdf(pdfdoc, inputPath + file.inputFile);
                        pdfdoc.Save(outputPath + file.outputFile, SDFDoc.SaveOptions.e_linearized);
                        Console.WriteLine("Converted file: " + file.inputFile);
                        Console.WriteLine("to: " + file.outputFile);
                    }
                }
                catch (PDFNetException e)
                {
                    Console.WriteLine("ERROR: on input file " + file.inputFile);
                    Console.WriteLine(e.Message);
                    err = true;
                }
            }

            if (uninstallPrinterWhenDone)
            {
                try
                {
                    Console.WriteLine("Uninstalling printer (requires administrator)");
                    pdftron.PDF.Convert.Printer.Uninstall();
                    Console.WriteLine("Uninstalled printer " + pdftron.PDF.Convert.Printer.GetPrinterName());
                }
                catch (PDFNetException e)
                {
                    Console.WriteLine(e.Message);
                    err = true;
                }
            }
            return(err);
        }
        static Boolean ConvertSpecificFormats()
        {
            //////////////////////////////////////////////////////////////////////////
            Boolean err = false;

            try
            {
                using (PDFDoc pdfdoc = new PDFDoc())
                {
                    Console.WriteLine("Converting from XPS");

                    pdftron.PDF.Convert.FromXps(pdfdoc, inputPath + "simple-xps.xps");
                    pdfdoc.Save(outputPath + "xps2pdf v2.pdf", SDFDoc.SaveOptions.e_remove_unused);
                    Console.WriteLine("Saved xps2pdf v2.pdf");
                }
            }
            catch (PDFNetException e)
            {
                Console.WriteLine(e.Message);
                err = true;
            }

            //////////////////////////////////////////////////////////////////////////
            try
            {
                using (PDFDoc pdfdoc = new PDFDoc())
                {
                    Console.WriteLine("Converting from EMF");
                    pdftron.PDF.Convert.FromEmf(pdfdoc, inputPath + "simple-emf.emf");
                    pdfdoc.Save(outputPath + "emf2pdf v2.pdf", SDFDoc.SaveOptions.e_remove_unused);
                    Console.WriteLine("Saved emf2pdf v2.pdf");
                }
            }
            catch (PDFNetException e)
            {
                Console.WriteLine(e.Message);
                err = true;
            }

            //////////////////////////////////////////////////////////////////////////
            try
            {
                using (PDFDoc pdfdoc = new PDFDoc())
                {
                    // Add a dictionary
                    ObjSet set     = new ObjSet();
                    Obj    options = set.CreateDict();

                    // Put options
                    options.PutNumber("FontSize", 15);
                    options.PutBool("UseSourceCodeFormatting", true);
                    options.PutNumber("PageWidth", 12);
                    options.PutNumber("PageHeight", 6);

                    // Convert from .txt file
                    Console.WriteLine("Converting from txt");
                    pdftron.PDF.Convert.FromText(pdfdoc, inputPath + "simple-text.txt", options);
                    pdfdoc.Save(outputPath + "simple-text.pdf", SDFDoc.SaveOptions.e_remove_unused);
                    Console.WriteLine("Saved simple-text.pdf");
                }
            }
            catch (PDFNetException e)
            {
                Console.WriteLine(e.Message);
                err = true;
            }

            //////////////////////////////////////////////////////////////////////////
            try
            {
                using (PDFDoc pdfdoc = new PDFDoc(inputPath + "newsletter.pdf"))
                {
                    // Convert PDF document to SVG
                    Console.WriteLine("Converting pdfdoc to SVG");
                    pdftron.PDF.Convert.ToSvg(pdfdoc, outputPath + "pdf2svg v2.svg");
                    Console.WriteLine("Saved pdf2svg v2.svg");
                }
            }
            catch (PDFNetException e)
            {
                Console.WriteLine(e.Message);
                err = true;
            }

            //////////////////////////////////////////////////////////////////////////
            try
            {
                // Convert PNG image to XPS
                Console.WriteLine("Converting PNG to XPS");
                pdftron.PDF.Convert.ToXps(inputPath + "butterfly.png", outputPath + "butterfly.xps");
                Console.WriteLine("Saved butterfly.xps");
            }
            catch (PDFNetException e)
            {
                Console.WriteLine(e.Message);
                err = true;
            }

            //////////////////////////////////////////////////////////////////////////
            try
            {
                // Convert MSWord document to XPS
                Console.WriteLine("Converting DOCX to XPS");
                pdftron.PDF.Convert.ToXps(inputPath + "simple-word_2007.docx", outputPath + "simple-word_2007.xps");
                Console.WriteLine("Saved simple-word_2007.xps");
            }
            catch (PDFNetException e)
            {
                Console.WriteLine(e.Message);
                err = true;
            }

            //////////////////////////////////////////////////////////////////////////
            try
            {
                // Convert PDF document to XPS
                Console.WriteLine("Converting PDF to XPS");
                pdftron.PDF.Convert.ToXps(inputPath + "newsletter.pdf", outputPath + "newsletter.xps");
                Console.WriteLine("Saved newsletter.xps");
            }
            catch (PDFNetException e)
            {
                Console.WriteLine(e.Message);
                err = true;
            }

            //////////////////////////////////////////////////////////////////////////
            try
            {
                // Convert PDF document to HTML
                Console.WriteLine("Converting PDF to HTML");
                pdftron.PDF.Convert.ToHtml(inputPath + "newsletter.pdf", outputPath + "newsletter");
                Console.WriteLine("Saved newsletter as HTML");
            }
            catch (PDFNetException e)
            {
                Console.WriteLine(e.Message);
                err = true;
            }

            //////////////////////////////////////////////////////////////////////////
            try
            {
                // Convert PDF document to EPUB
                Console.WriteLine("Converting PDF to EPUB");
                pdftron.PDF.Convert.ToEpub(inputPath + "newsletter.pdf", outputPath + "newsletter.epub");
                Console.WriteLine("Saved newsletter.epub");
            }
            catch (PDFNetException e)
            {
                Console.WriteLine(e.Message);
                err = true;
            }

            //////////////////////////////////////////////////////////////////////////
            try
            {
                // Convert PDF document to multipage TIFF
                Console.WriteLine("Converting PDF to multipage TIFF");
                pdftron.PDF.Convert.TiffOutputOptions tiff_options = new pdftron.PDF.Convert.TiffOutputOptions();
                tiff_options.SetDPI(200);
                tiff_options.SetDither(true);
                tiff_options.SetMono(true);
                pdftron.PDF.Convert.ToTiff(inputPath + "newsletter.pdf", outputPath + "newsletter.tiff", tiff_options);
                Console.WriteLine("Saved newsletter.tiff");
            }
            catch (PDFNetException e)
            {
                Console.WriteLine(e.Message);
                err = true;
            }

            return(err);
        }
        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();
            try
            {
                using (PDFDoc doc = new PDFDoc())
                    using (ElementWriter writer = new ElementWriter())
                        using (ElementBuilder eb = new ElementBuilder())
                        {
                            // The following sample illustrates how to create and use tiling patterns
                            Page page = doc.PageCreate();
                            writer.Begin(page);

                            Element element = eb.CreateTextBegin(Font.Create(doc, Font.StandardType1Font.e_times_bold), 1);
                            writer.WriteElement(element);              // Begin the text block

                            element = eb.CreateTextRun("G");
                            element.SetTextMatrix(720, 0, 0, 720, 20, 240);
                            GState gs = element.GetGState();
                            gs.SetTextRenderMode(GState.TextRenderingMode.e_fill_stroke_text);
                            gs.SetLineWidth(4);

                            // Set the fill color space to the Pattern color space.
                            gs.SetFillColorSpace(ColorSpace.CreatePattern());
                            gs.SetFillColor(CreateTilingPattern(doc));

                            writer.WriteElement(element);
                            writer.WriteElement(eb.CreateTextEnd()); // Finish the text block

                            writer.End();                            // Save the page
                            doc.PagePushBack(page);
                            //-----------------------------------------------

                            /// The following sample illustrates how to create and use image tiling pattern
                            page = doc.PageCreate();
                            writer.Begin(page);

                            eb.Reset();
                            element = eb.CreateRect(0, 0, 612, 794);

                            // Set the fill color space to the Pattern color space.
                            gs = element.GetGState();
                            gs.SetFillColorSpace(ColorSpace.CreatePattern());
                            gs.SetFillColor(CreateImageTilingPattern(doc));
                            element.SetPathFill(true);

                            writer.WriteElement(element);

                            writer.End();               // Save the page
                            doc.PagePushBack(page);
                            //-----------------------------------------------

                            /// The following sample illustrates how to create and use PDF shadings
                            page = doc.PageCreate();
                            writer.Begin(page);

                            eb.Reset();
                            element = eb.CreateRect(0, 0, 612, 794);

                            // Set the fill color space to the Pattern color space.
                            gs = element.GetGState();
                            gs.SetFillColorSpace(ColorSpace.CreatePattern());
                            gs.SetFillColor(CreateAxialShading(doc));
                            element.SetPathFill(true);

                            writer.WriteElement(element);

                            writer.End();               // save the page
                            doc.PagePushBack(page);
                            //-----------------------------------------------

                            doc.Save(output_path + "patterns.pdf", SDFDoc.SaveOptions.e_remove_unused);
                            Console.WriteLine("Done. Result saved in patterns.pdf...");
                        }
            }
            catch (PDFNetException e)
            {
                Console.WriteLine(e.Message);
            }
        }
        // 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;
            }
        }
Exemple #27
0
        static void Main(string[] args)
        {
            string output_path = "../../TestFiles/Output/html2pdf_example";
            string host        = "http://www.gutenberg.org/";
            string page0       = "wiki/Main_Page";
            string page1       = "catalog/";
            string page2       = "browse/recent/last1";
            string page3       = "wiki/Gutenberg:The_Sheet_Music_Project";

            // 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();

            // For HTML2PDF we need to locate the html2pdf module. If placed with the
            // PDFNet library, or in the current working directory, it will be loaded
            // automatically. Otherwise, it must be set manually using HTML2PDF.SetModulePath.
            HTML2PDF.SetModulePath("../../../../../Lib");

            //--------------------------------------------------------------------------------
            // Example 1) Simple conversion of a web page to a PDF doc.

            try
            {
                using (PDFDoc doc = new PDFDoc())
                {
                    // now convert a web page, sending generated PDF pages to doc
                    if (HTML2PDF.Convert(doc, host + page0))
                    {
                        doc.Save(output_path + "_01.pdf", SDFDoc.SaveOptions.e_linearized);
                    }
                    else
                    {
                        Console.WriteLine("Conversion failed.");
                    }
                }
            }
            catch (PDFNetException e)
            {
                Console.WriteLine(e.Message);
            }

            //--------------------------------------------------------------------------------
            // Example 2) Modify the settings of the generated PDF pages and attach to an
            // existing PDF document.

            try
            {
                // open the existing PDF, and initialize the security handler
                using (PDFDoc doc = new PDFDoc("../../TestFiles/numbered.pdf"))
                {
                    doc.InitSecurityHandler();

                    // create the HTML2PDF converter object and modify the output of the PDF pages
                    HTML2PDF converter = new HTML2PDF();
                    converter.SetImageQuality(25);
                    converter.SetPaperSize(PrinterMode.PaperSize.e_11x17);

                    // insert the web page to convert
                    converter.InsertFromURL(host + page0);

                    // convert the web page, appending generated PDF pages to doc
                    if (converter.Convert(doc))
                    {
                        doc.Save(output_path + "_02.pdf", SDFDoc.SaveOptions.e_linearized);
                    }
                    else
                    {
                        Console.WriteLine("Conversion failed. HTTP Code: {0}\n{1}", converter.GetHTTPErrorCode(), converter.GetLog());
                    }
                }
            }
            catch (PDFNetException e)
            {
                Console.WriteLine(e.Message);
            }

            //--------------------------------------------------------------------------------
            // Example 3) Convert multiple web pages, adding a table of contents, and setting
            // the first page as a cover page, not to be included with the table of contents outline.

            try
            {
                using (PDFDoc doc = new PDFDoc())
                {
                    HTML2PDF converter = new HTML2PDF();

                    // Add a cover page, which is excluded from the outline, and ignore any errors
                    HTML2PDF.WebPageSettings cover = new HTML2PDF.WebPageSettings();
                    cover.SetLoadErrorHandling(HTML2PDF.WebPageSettings.ErrorHandling.e_ignore);
                    cover.SetIncludeInOutline(false);
                    converter.InsertFromURL(host + page3, cover);

                    // Add a table of contents settings (modifying the settings is optional)
                    HTML2PDF.TOCSettings toc = new HTML2PDF.TOCSettings();
                    toc.SetDottedLines(false);
                    converter.InsertTOC(toc);

                    // Now add the rest of the web pages, disabling external links and
                    // skipping any web pages that fail to load.
                    //
                    // Note that the order of insertion matters, so these will appear
                    // after the cover and table of contents, in the order below.
                    HTML2PDF.WebPageSettings settings = new HTML2PDF.WebPageSettings();
                    settings.SetLoadErrorHandling(HTML2PDF.WebPageSettings.ErrorHandling.e_skip);
                    settings.SetExternalLinks(false);
                    converter.InsertFromURL(host + page0, settings);
                    converter.InsertFromURL(host + page1, settings);
                    converter.InsertFromURL(host + page2, settings);

                    if (converter.Convert(doc))
                    {
                        doc.Save(output_path + "_03.pdf", SDFDoc.SaveOptions.e_linearized);
                    }
                    else
                    {
                        Console.WriteLine("Conversion failed. HTTP Code: {0}\n{1}", converter.GetHTTPErrorCode(), converter.GetLog());
                    }
                }
            }
            catch (PDFNetException e)
            {
                Console.WriteLine(e.Message);
            }

            //--------------------------------------------------------------------------------
            // Example 4) Convert HTML string to PDF.

            try
            {
                using (PDFDoc doc = new PDFDoc())
                {
                    HTML2PDF converter = new HTML2PDF();

                    // Our HTML data
                    string html = "<html><body><h1>Heading</h1><p>Paragraph.</p></body></html>";

                    // Add html data
                    converter.InsertFromHtmlString(html);
                    // Note, InsertFromHtmlString can be mixed with the other Insert methods.

                    if (converter.Convert(doc))
                    {
                        doc.Save(output_path + "_04.pdf", SDFDoc.SaveOptions.e_linearized);
                    }
                    else
                    {
                        Console.WriteLine("Conversion failed. HTTP Code: {0}\n{1}", converter.GetHTTPErrorCode(), converter.GetLog());
                    }
                }
            }
            catch (PDFNetException e)
            {
                Console.WriteLine(e.Message);
            }
        }
Exemple #28
0
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main()
        {
            // Initialize PDFNet before calling any other PDFNet function.
            PDFNet.Initialize();

            string input_path     = "../../TestFiles/";
            string output_path    = "../../TestFiles/Output/";
            string input_filename = "US061222892-a.pdf";

            PDFDoc pdf_doc = new PDFDoc(input_path + input_filename);

            pdf_doc.InitSecurityHandler();

            SDFDoc cos_doc  = pdf_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;
                    }

                    pdftron.PDF.Image input_image = new pdftron.PDF.Image(obj);
                    pdftron.PDF.Image new_image   = null;

                    // Process only gray-scale images
                    if (input_image.GetComponentNum() != 1)
                    {
                        continue;
                    }

                    int bpc = input_image.GetBitsPerComponent();
                    if (bpc != 1)                     // Recompress 1 BPC images
                    {
                        continue;
                    }

                    // Skip images that are already compressed using JBIG2
                    itr = obj.Find("Filter");
                    if (itr.HasNext() && itr.Value().IsName() &&
                        itr.Value().GetName() == "JBIG2Decode")
                    {
                        continue;
                    }

                    FilterReader reader = new FilterReader(obj.GetDecodedStream());

                    ObjSet hint_set = new ObjSet();
                    Obj    hint     = hint_set.CreateArray();
                    hint.PushBackName("JBIG2");
                    hint.PushBackName("Lossless");
                    hint.PushBackName("Threshold");
                    hint.PushBackNumber(0.4);
                    hint.PushBackName("SharePages");
                    hint.PushBackNumber(10000);

                    new_image = pdftron.PDF.Image.Create(
                        cos_doc,
                        reader,
                        input_image.GetImageWidth(),
                        input_image.GetImageHeight(),
                        1,
                        ColorSpace.CreateDeviceGray(),
                        hint                          // A hint to image encoder to use JBIG2 compression
                        );

                    Obj new_img_obj = new_image.GetSDFObj();

                    // Copy any important entries from the image dictionary
                    itr = obj.Find("ImageMask");
                    if (itr.HasNext())
                    {
                        new_img_obj.Put("ImageMask", itr.Value());
                    }

                    itr = obj.Find("Mask");
                    if (itr.HasNext())
                    {
                        new_img_obj.Put("Mask", itr.Value());
                    }

                    cos_doc.Swap(i, new_image.GetSDFObj().GetObjNum());
                }
            }

            pdf_doc.Save(output_path + "US061222892_JBIG2.pdf", SDFDoc.SaveOptions.e_remove_unused);
            pdf_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
            {
                // 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/";

            // Sample code showing how to use high-level text extraction APIs.
            try
            {
                using (PDFDoc doc = new PDFDoc(input_path + "credit card numbers.pdf"))
                {
                    doc.InitSecurityHandler();

                    Int32      page_num = 0;
                    String     result_str = "", ambient_string = "";
                    Highlights hlts = new Highlights();

                    TextSearch txt_search = new TextSearch();
                    Int32      mode       = (Int32)(TextSearch.SearchMode.e_whole_word | TextSearch.SearchMode.e_page_stop | TextSearch.SearchMode.e_highlight);
                    String     pattern    = "joHn sMiTh";

                    //call Begin() method to initialize the text search.
                    txt_search.Begin(doc, pattern, mode, -1, -1);

                    int step = 0;

                    //call Run() method iteratively to find all matching instances.
                    while (true)
                    {
                        TextSearch.ResultCode code = txt_search.Run(ref page_num, ref result_str, ref ambient_string, hlts);

                        if (code == TextSearch.ResultCode.e_found)
                        {
                            if (step == 0)
                            {                                   //step 0: found "John Smith"
                                                                //note that, here, 'ambient_string' and 'hlts' are not written to,
                                                                //as 'e_ambient_string' and 'e_highlight' are not set.
                                Console.WriteLine(result_str + "'s credit card number is: ");

                                //now switch to using regular expressions to find John's credit card number
                                mode  = txt_search.GetMode();
                                mode |= (Int32)(TextSearch.SearchMode.e_reg_expression | TextSearch.SearchMode.e_highlight);
                                txt_search.SetMode(mode);
                                pattern = "\\d{4}-\\d{4}-\\d{4}-\\d{4}";                                 //or "(\\d{4}-){3}\\d{4}"
                                txt_search.SetPattern(pattern);

                                ++step;
                            }
                            else if (step == 1)
                            {
                                //step 1: found John's credit card number
                                //result_str.ConvertToAscii(char_buf, 32, true);
                                //cout << "  " << char_buf << endl;
                                Console.WriteLine("  " + result_str);

                                //note that, here, 'hlts' is written to, as 'e_highlight' has been set.
                                //output the highlight info of the credit card number
                                hlts.Begin(doc);
                                while (hlts.HasNext())
                                {
                                    Console.WriteLine("The current highlight is from page: " + hlts.GetCurrentPageNumber());
                                    hlts.Next();
                                }

                                //see if there is an AMEX card number
                                pattern = "\\d{4}-\\d{6}-\\d{5}";
                                txt_search.SetPattern(pattern);

                                ++step;
                            }
                            else if (step == 2)
                            {
                                //found an AMEX card number
                                Console.WriteLine("\nThere is an AMEX card number:\n  " + result_str);

                                //change mode to find the owner of the credit card; supposedly, the owner's
                                //name proceeds the number
                                mode  = txt_search.GetMode();
                                mode |= (Int32)(TextSearch.SearchMode.e_search_up);
                                txt_search.SetMode(mode);
                                pattern = "[A-z]++ [A-z]++";
                                txt_search.SetPattern(pattern);

                                ++step;
                            }
                            else if (step == 3)
                            {
                                //found the owner's name of the AMEX card
                                Console.WriteLine("Is the owner's name:\n  " + result_str + "?");

                                //add a link annotation based on the location of the found instance
                                hlts.Begin(doc);
                                while (hlts.HasNext())
                                {
                                    Page     cur_page   = doc.GetPage(hlts.GetCurrentPageNumber());
                                    double[] quads      = hlts.GetCurrentQuads();
                                    int      quad_count = quads.Length / 8;
                                    for (int i = 0; i < quad_count; ++i)
                                    {
                                        //assume each quad is an axis-aligned rectangle
                                        int    offset = 8 * i;
                                        double x1     = Math.Min(Math.Min(Math.Min(quads[offset + 0], quads[offset + 2]), quads[offset + 4]), quads[offset + 6]);
                                        double x2     = Math.Max(Math.Max(Math.Max(quads[offset + 0], quads[offset + 2]), quads[offset + 4]), quads[offset + 6]);
                                        double y1     = Math.Min(Math.Min(Math.Min(quads[offset + 1], quads[offset + 3]), quads[offset + 5]), quads[offset + 7]);
                                        double y2     = Math.Max(Math.Max(Math.Max(quads[offset + 1], quads[offset + 3]), quads[offset + 5]), quads[offset + 7]);

                                        pdftron.PDF.Annots.Link hyper_link = pdftron.PDF.Annots.Link.Create(doc, new Rect(x1, y1, x2, y2), pdftron.PDF.Action.CreateURI(doc, "http://www.pdftron.com"));
                                        hyper_link.RefreshAppearance();
                                        cur_page.AnnotPushBack(hyper_link);
                                    }
                                    hlts.Next();
                                }
                                string output_path = "../../TestFiles/Output/";
                                doc.Save(output_path + "credit card numbers_linked.pdf", SDFDoc.SaveOptions.e_linearized);

                                break;
                            }
                        }
                        else if (code == TextSearch.ResultCode.e_page)
                        {
                            //you can update your UI here, if needed
                        }
                        else
                        {
                            break;
                        }
                    }
                }
            }

            catch (PDFNetException e)
            {
                Console.WriteLine(e.Message);
            }
        }
        /// <summary>
        /// Genera la factura de la reserva id pasada como parametro, si la factura pertenece al socio y si ha pagado la reserva, y la devuelve al socio
        /// </summary>
        /// <param name="id">id de la reserva para la cual mostrar la factura</param>
        /// <returns>pdf con la factura si socio, sino redirige a /Home/index o /Admin/index dependiendo si es admin o no logueado</returns>
        public ActionResult VerFacturaReserva(int? id)
        {
            if (isSocio())
            {
                reservas reserva = db.reservas.Find(id);
                if (reserva == null)
                {
                    addError("No tiene permisos para visualizar esta reserva");
                    saveErrors();
                    return RedirectToAction("MisReservas", "Socio");
                }
                string socio_id = (string)Session["UserID"];
                if (reserva.socios.id != socio_id)
                {
                    addError("No tiene permisos para visualizar esta reserva");
                    saveErrors();
                    return RedirectToAction("MisReservas", "Socio");
                }
                if (reserva.pagado == false)
                {
                    addError("La factura no puede ser visualizada hasta que la reserva sea abonada");
                    saveErrors();
                    return RedirectToAction("MisReservas", "Socio");
                }

                // Creacion del pdf a partir de los datos xml en la BBDD
                PDFNet.Initialize();

                // Ruta relavita a las carpetas que contienen los archivos
                string input_path = "c:/Google Drive/PFC/pdf/";
                string output_path = "c:/Google Drive/PFC/pdf/Output/";
                try
                {
                    // Juntar XFDF desde el xml string
                    PDFDoc in_doc = new PDFDoc(input_path + "factura.pdf");
                    {
                        in_doc.InitSecurityHandler();

                        //Debug.WriteLine("Juntamos XFDF string con el PDF...");

                        //reservas reserva = db.reservas.Find(id);
                        string str = reserva.facturas.xml_factura;
                        //Debug.WriteLine(str);

                        using (FDFDoc fdoc = new FDFDoc(FDFDoc.CreateFromXFDF(str)))
                        {
                            in_doc.FDFMerge(fdoc);
                            // Iniciamos los permisos del pdf, para que no se pueda editar
                            StdSecurityHandler newHandler = new StdSecurityHandler();
                            newHandler.SetPermission(SecurityHandler.Permission.e_doc_modify, false);
                            newHandler.SetPermission(SecurityHandler.Permission.e_fill_forms, false);
                            newHandler.SetPermission(SecurityHandler.Permission.e_extract_content, false);
                            newHandler.SetPermission(SecurityHandler.Permission.e_mod_annot, false);

                            in_doc.SetSecurityHandler(newHandler);
                            in_doc.Save(output_path + "factura_modificada.pdf", SDFDoc.SaveOptions.e_linearized);
                            Debug.WriteLine("Juntado completado.");
                        }
                    }
                }
                catch (PDFNetException e)
                {
                    Debug.WriteLine(e.Message);
                }

                return File("c:/Google drive/PFC/pdf/output/factura_modificada.pdf", "application/pdf");
            }
            else
                return RedirectToAction("Index", isAdmin() ? "Admin" : "Home");
        }
Exemple #32
0
        /// <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();

            // Can optionally set path to the OCR module
            PDFNet.AddResourceSearchPath("../../../../../Lib/");
            if (!OCRModule.IsModuleAvailable())
            {
                Console.WriteLine("");
                Console.WriteLine("Unable to run OCRTest: PDFTron SDK OCR module not available.");
                Console.WriteLine("---------------------------------------------------------------");
                Console.WriteLine("The OCR module is an optional add-on, available for download");
                Console.WriteLine("at http://www.pdftron.com/. If you have already downloaded this");
                Console.WriteLine("module, ensure that the SDK is able to find the required files");
                Console.WriteLine("using the PDFNet.AddResourceSearchPath() function.");
                Console.WriteLine("");
                return;
            }

            // Relative path to the folder containing test files.
            string input_path  = "../../TestFiles/OCR/";
            string output_path = "../../TestFiles/Output/";

            //--------------------------------------------------------------------------------
            // Example 1) Process image
            try
            {
                // A) Setup empty destination doc
                using (PDFDoc doc = new PDFDoc())
                {
                    // B) Set English as the language of choice
                    OCROptions opts = new OCROptions();
                    opts.AddLang("eng");

                    // C) Run OCR on the .png with options
                    OCRModule.ImageToPDF(doc, input_path + "psychomachia_excerpt.png", opts);

                    // D) check the result
                    doc.Save(output_path + "psychomachia_excerpt.pdf", SDFDoc.SaveOptions.e_remove_unused);

                    Console.WriteLine("Example 1: psychomachia_excerpt.png");
                }
            }
            catch (PDFNetException e)
            {
                Console.WriteLine(e.Message);
            }

            //--------------------------------------------------------------------------------
            // Example 2) Process document using multiple languages
            try
            {
                // A) Setup empty destination doc
                using (PDFDoc doc = new PDFDoc())
                {
                    // B) Setup options with multiple target languages, English will always be considered as secondary language
                    OCROptions opts = new OCROptions();
                    opts.AddLang("rus");
                    opts.AddLang("deu");

                    // C) Run OCR on the .jpg with options
                    OCRModule.ImageToPDF(doc, input_path + "multi_lang.jpg", opts);

                    // D) check the result
                    doc.Save(output_path + "multi_lang.pdf", SDFDoc.SaveOptions.e_remove_unused);

                    Console.WriteLine("Example 2: multi_lang.jpg");
                }
            }
            catch (PDFNetException e)
            {
                Console.WriteLine(e.Message);
            }

            //--------------------------------------------------------------------------------
            // Example 3) Process a .pdf specifying a language - German - and ignore zone comprising a sidebar image
            try
            {
                // A) Open the .pdf document
                using (PDFDoc doc = new PDFDoc(input_path + "german_kids_song.pdf"))
                {
                    // B) Setup options with a single language and an ignore zone
                    OCROptions opts = new OCROptions();
                    opts.AddLang("deu");

                    RectCollection ignoreZones = new RectCollection();
                    ignoreZones.AddRect(1768, 680, 2056, 3044);
                    opts.AddIgnoreZonesForPage(ignoreZones, 1);

                    // C) Run OCR on the .pdf with options
                    OCRModule.ProcessPDF(doc, opts);

                    // D) check the result
                    doc.Save(output_path + "german_kids_song.pdf", SDFDoc.SaveOptions.e_remove_unused);

                    Console.WriteLine("Example 3: german_kids_song.pdf");
                }
            }
            catch (PDFNetException e)
            {
                Console.WriteLine(e.Message);
            }

            //--------------------------------------------------------------------------------
            // Example 4) Process multipage tiff with text/ignore zones specified for each page
            try
            {
                // A) Setup empty destination doc
                using (PDFDoc doc = new PDFDoc())
                {
                    // B) Setup options with a single language plus text/ignore zones
                    OCROptions opts = new OCROptions();
                    opts.AddLang("eng");

                    RectCollection zones = new RectCollection();


                    // ignore signature box in the first 2 pages
                    zones.AddRect(1492, 56, 2236, 432);
                    opts.AddIgnoreZonesForPage(zones, 1);
                    zones.Clear();

                    zones.AddRect(1492, 56, 2236, 432);
                    opts.AddIgnoreZonesForPage(zones, 2);
                    zones.Clear();

                    // can use a combination of ignore and text boxes to focus on the page area of interest,
                    // as ignore boxes are applied first, we remove the arrows before selecting part of the diagram
                    zones.AddRect(992, 1276, 1368, 1372);
                    opts.AddIgnoreZonesForPage(zones, 3);
                    zones.Clear();

                    // select horizontal BUFFER ZONE sign
                    zones.AddRect(900, 2384, 1236, 2480);
                    // select right vertical BUFFER ZONE sign
                    zones.AddRect(1960, 1976, 2016, 2296);
                    // select Lot No.
                    zones.AddRect(696, 1028, 1196, 1128);

                    // select part of the plan inside the BUFFER ZONE
                    zones.AddRect(428, 1484, 1784, 2344);
                    zones.AddRect(948, 1288, 1672, 1476);
                    opts.AddTextZonesForPage(zones, 3);

                    // C) Run OCR on the .pdf with options
                    OCRModule.ImageToPDF(doc, input_path + "bc_environment_protection.tif", opts);

                    // D) check the result
                    doc.Save(output_path + "bc_environment_protection.pdf", SDFDoc.SaveOptions.e_remove_unused);

                    Console.WriteLine("Example 4: bc_environment_protection.tif");
                }
            }
            catch (PDFNetException e)
            {
                Console.WriteLine(e.Message);
            }

            //--------------------------------------------------------------------------------
            // Example 5) Alternative workflow for extracting OCR result JSON, postprocessing (e.g., removing words not in the dictionary or filtering special
            // out special characters), and finally applying modified OCR JSON to the source PDF document
            try
            {
                // A) Open the .pdf document
                using (PDFDoc doc = new PDFDoc(input_path + "zero_value_test_no_text.pdf"))
                {
                    // B) set English language
                    OCROptions opts = new OCROptions();
                    opts.AddLang("eng");


                    // C) Run OCR on the .pdf
                    string json = OCRModule.GetOCRJsonFromPDF(doc, opts);

                    // D) Post-processing step (whatever it might be), but we just print JSON here
                    Console.WriteLine("Have OCR result JSON, re-applying to PDF");

                    // E) Apply potentially modified OCR JSON to the PDF
                    OCRModule.ApplyOCRJsonToPDF(doc, json);

                    // F) check the result
                    doc.Save(output_path + "zero_value_test_no_text.pdf", SDFDoc.SaveOptions.e_remove_unused);

                    Console.WriteLine("Example 5: extracting and applying OCR JSON from zero_value_test_no_text.pdf");
                }
            }
            catch (PDFNetException e)
            {
                Console.WriteLine(e.Message);
            }

            //--------------------------------------------------------------------------------
            // Example 6) The postprocessing workflow has also an option of extracting OCR results in XML format, similar to the one used by TextExtractor
            try
            {
                // A) Setup empty destination doc
                using (PDFDoc doc = new PDFDoc())
                {
                    // B) set English language
                    OCROptions opts = new OCROptions();
                    opts.AddLang("eng");

                    // C) Run OCR on the .tif with default English language, extracting OCR results in XML format. Note that
                    // in the process we convert the source image into PDF. We reuse this PDF document later to add hidden text layer to it.

                    string xml = OCRModule.GetOCRXmlFromImage(doc, input_path + "physics.tif", opts);

                    // D) Post-processing step (whatever it might be), but we just print XML here
                    Console.WriteLine("Have OCR result XML, re-applying to PDF");

                    // E) Apply potentially modified OCR XML to the PDF
                    OCRModule.ApplyOCRXmlToPDF(doc, xml);

                    // F) check the result
                    doc.Save(output_path + "physics.pdf", SDFDoc.SaveOptions.e_remove_unused);

                    Console.WriteLine("Example 6: extracting and applying OCR XML from physics.tif");
                }
            }
            catch (PDFNetException e)
            {
                Console.WriteLine(e.Message);
            }
        }
Exemple #33
0
        /// <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/";

            // Example 1)
            // Iterate over all form fields in the document. Display all field names.
            try
            {
                using (PDFDoc doc = new PDFDoc(input_path + "form1.pdf"))
                {
                    doc.InitSecurityHandler();

                    FieldIterator itr;
                    for (itr = doc.GetFieldIterator(); itr.HasNext(); itr.Next())
                    {
                        Console.WriteLine("Field name: {0:s}", itr.Current().GetName());
                        Console.WriteLine("Field partial name: {0:s}", itr.Current().GetPartialName());

                        Console.Write("Field type: ");
                        Field.Type type = itr.Current().GetType();
                        switch (type)
                        {
                        case Field.Type.e_button:
                            Console.WriteLine("Button"); break;

                        case Field.Type.e_text:
                            Console.WriteLine("Text"); break;

                        case Field.Type.e_choice:
                            Console.WriteLine("Choice"); break;

                        case Field.Type.e_signature:
                            Console.WriteLine("Signature"); break;
                        }

                        Console.WriteLine("------------------------------");
                    }

                    Console.WriteLine("Done.");
                }
            }
            catch (PDFNetException e)
            {
                Console.WriteLine(e.Message);
            }

            // Example 2) Import XFDF into FDF, then merge data from FDF into PDF
            try
            {
                // XFDF to FDF
                // form fields
                Console.WriteLine("Import form field data from XFDF to FDF.");

                FDFDoc fdf_doc1 = new FDFDoc(FDFDoc.CreateFromXFDF(input_path + "form1_data.xfdf"));
                fdf_doc1.Save(output_path + "form1_data.fdf");

                // annotations
                Console.WriteLine("Import annotations from XFDF to FDF.");

                FDFDoc fdf_doc2 = new FDFDoc(FDFDoc.CreateFromXFDF(input_path + "form1_annots.xfdf"));
                fdf_doc2.Save(output_path + "form1_annots.fdf");

                // FDF to PDF
                // form fields
                Console.WriteLine("Merge form field data from FDF.");

                using (PDFDoc doc = new PDFDoc(input_path + "form1.pdf"))
                {
                    doc.InitSecurityHandler();
                    doc.FDFMerge(fdf_doc1);

                    // To use PDFNet form field appearance generation instead of relying on
                    // Acrobat, uncomment the following two lines:
                    // doc.RefreshFieldAppearances();
                    // doc.GetAcroForm().Put("NeedAppearances", Obj.CreateBool(false));

                    doc.Save(output_path + "form1_filled.pdf", SDFDoc.SaveOptions.e_linearized);

                    // annotations
                    Console.WriteLine("Merge annotations from FDF.");

                    doc.FDFMerge(fdf_doc2);
                    doc.Save(output_path + "form1_filled_with_annots.pdf", SDFDoc.SaveOptions.e_linearized);

                    Console.WriteLine("Done.");
                }
            }
            catch (PDFNetException e)
            {
                Console.WriteLine(e.Message);
            }

            // Example 3) Extract data from PDF to FDF, then export FDF as XFDF
            try
            {
                // PDF to FDF
                using (PDFDoc in_doc = new PDFDoc(output_path + "form1_filled_with_annots.pdf"))
                {
                    in_doc.InitSecurityHandler();

                    // form fields only
                    Console.WriteLine("Extract form fields data to FDF.");

                    FDFDoc doc_fields = in_doc.FDFExtract(PDFDoc.ExtractFlag.e_forms_only);
                    doc_fields.SetPdfFileName("../form1_filled_with_annots.pdf");
                    doc_fields.Save(output_path + "form1_filled_data.fdf");

                    // annotations only
                    Console.WriteLine("Extract annotations to FDF.");

                    FDFDoc doc_annots = in_doc.FDFExtract(PDFDoc.ExtractFlag.e_annots_only);
                    doc_annots.SetPdfFileName("../form1_filled_with_annots.pdf");
                    doc_annots.Save(output_path + "form1_filled_annot.fdf");

                    // both form fields and annotations
                    Console.WriteLine("Extract both form fields and annotations to FDF.");

                    FDFDoc doc_both = in_doc.FDFExtract(PDFDoc.ExtractFlag.e_both);
                    doc_both.SetPdfFileName("../form1_filled_with_annots.pdf");
                    doc_both.Save(output_path + "form1_filled_both.fdf");

                    // FDF to XFDF
                    // form fields
                    Console.WriteLine("Export form field data from FDF to XFDF.");

                    doc_fields.SaveAsXFDF(output_path + "form1_filled_data.xfdf");

                    // annotations
                    Console.WriteLine("Export annotations from FDF to XFDF.");

                    doc_annots.SaveAsXFDF(output_path + "form1_filled_annot.xfdf");

                    // both form fields and annotations
                    Console.WriteLine("Export both form fields and annotations from FDF to XFDF.");

                    doc_both.SaveAsXFDF(output_path + "form1_filled_both.xfdf");

                    Console.WriteLine("Done.");
                }
            }
            catch (PDFNetException e)
            {
                Console.WriteLine(e.Message);
            }

            // Example 4) Merge/Extract XFDF into/from PDF
            try
            {
                // Merge XFDF from string
                PDFDoc in_doc = new PDFDoc(input_path + "numbered.pdf");
                {
                    in_doc.InitSecurityHandler();

                    Console.WriteLine("Merge XFDF string into PDF.");

                    string str = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?><xfdf xmlns=\"http://ns.adobe.com/xfdf\" xml:space=\"preserve\"><square subject=\"Rectangle\" page=\"0\" name=\"cf4d2e58-e9c5-2a58-5b4d-9b4b1a330e45\" title=\"user\" creationdate=\"D:20120827112326-07'00'\" date=\"D:20120827112326-07'00'\" rect=\"227.7814207650273,597.6174863387978,437.07103825136608,705.0491803278688\" color=\"#000000\" interior-color=\"#FFFF00\" flags=\"print\" width=\"1\"><popup flags=\"print,nozoom,norotate\" open=\"no\" page=\"0\" rect=\"0,792,0,792\" /></square></xfdf>";

                    using (FDFDoc fdoc = new FDFDoc(FDFDoc.CreateFromXFDF(str)))
                    {
                        in_doc.FDFMerge(fdoc);
                        in_doc.Save(output_path + "numbered_modified.pdf", SDFDoc.SaveOptions.e_linearized);
                        Console.WriteLine("Merge complete.");
                    }

                    // Extract XFDF as string
                    Console.WriteLine("Extract XFDF as a string.");
                    FDFDoc fdoc_new = in_doc.FDFExtract(PDFDoc.ExtractFlag.e_both);
                    string XFDF_str = fdoc_new.SaveAsXFDF();
                    Console.WriteLine("Extracted XFDF: ");
                    Console.WriteLine(XFDF_str);
                    Console.WriteLine("Extract complete.");
                }
            }
            catch (PDFNetException e)
            {
                Console.WriteLine(e.Message);
            }

            // Example 5) Read FDF files directly
            try
            {
                FDFDoc           doc = new FDFDoc(output_path + "form1_filled_data.fdf");
                FDFFieldIterator itr = doc.GetFieldIterator();
                for (; itr.HasNext(); itr.Next())
                {
                    Console.WriteLine("Field name: {0:s}", itr.Current().GetName());
                    Console.WriteLine("Field partial name: {0:s}", itr.Current().GetPartialName());
                    Console.WriteLine("------------------------------");
                }

                Console.WriteLine("Done.");
            }
            catch (PDFNetException e)
            {
                Console.WriteLine(e.Message);
            }

            // Example 6) Direct generation of FDF.
            try
            {
                FDFDoc doc = new FDFDoc();

                // Create new fields (i.e. key/value pairs).
                doc.FieldCreate("Company", (int)Field.Type.e_text, "PDFTron Systems");
                doc.FieldCreate("First Name", (int)Field.Type.e_text, "John");
                doc.FieldCreate("Last Name", (int)Field.Type.e_text, "Doe");
                // ...

                // doc.SetPdfFileName("mydoc.pdf");
                doc.Save(output_path + "sample_output.fdf");
                Console.WriteLine("Done. Results saved in sample_output.fdf");
            }
            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);
            }
        }
        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;
            }
        }
        // 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/";


            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 void btnConvertToPdf_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(tbConvertPdf.Text))
            {
                ofdAbrirArquivo.Multiselect = false;
                ofdAbrirArquivo.Filter      = string.Empty;

                if (ofdAbrirArquivo.ShowDialog() == DialogResult.OK)
                {
                    using (PDFDoc doc = new PDFDoc())
                    {
                        try
                        {
                            switch (GetFileType(ofdAbrirArquivo.FileName))
                            {
                            case FileType.MSOffice:
                                pdftron.PDF.Convert.OfficeToPDF(doc, ofdAbrirArquivo.FileName, null);
                                break;

                            case FileType.HTML:
                                HTML2PDF converter = new HTML2PDF();

                                var htmlString = System.IO.File.ReadAllText(ofdAbrirArquivo.FileName);

                                converter.InsertFromHtmlString(htmlString);

                                converter.Convert(doc);
                                break;

                            case FileType.Other:
                                pdftron.PDF.Convert.ToPdf(doc, ofdAbrirArquivo.FileName);
                                break;

                            case FileType.NotMapped:
                                MessageBox.Show($"Extensão {GetFileExtension(ofdAbrirArquivo.FileName)} não mapeada");
                                return;

                            default:
                                break;
                            }

                            doc.Save(GetNewFileName(ofdAbrirArquivo.FileName, FileNameOptionEnum.Convert), SDFDoc.SaveOptions.e_linearized);
                        }
                        catch (PDFNetException ex)
                        {
                            MessageBox.Show(ex.Message);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message);
                        }
                    }
                }
            }
            else
            {
                using (PDFDoc doc = new PDFDoc())
                {
                    //HTML2PDF.Convert(doc, tbConvertPdf.Text);

                    HTML2PDF converter = new HTML2PDF();

                    converter.InsertFromURL(tbConvertPdf.Text);

                    converter.Convert(doc);

                    MessageBox.Show(converter.GetLog());

                    doc.Save(GetNewFileName("teste_convert-from-html", FileNameOptionEnum.Convert), SDFDoc.SaveOptions.e_linearized);
                }
            }
        }