Ejemplo n.º 1
0
        static void Main(string[] args)
        {
            PDFNet.Initialize();
            // Relative path to the folder containing test files.
            string input_path  = "../../TestFiles/";
            string output_path = "../../TestFiles/Output/";

            Console.WriteLine("_______________________________________________");
            Console.WriteLine("Opening the input pdf...");

            try             // Test  - Adjust the position of content within the page.
            {
                using (PDFDoc input_doc = new PDFDoc(input_path + "tiger.pdf"))
                {
                    input_doc.InitSecurityHandler();

                    Page pg        = input_doc.GetPage(1);
                    Rect media_box = pg.GetMediaBox();

                    media_box.x1 -= 200;                        // translate the page 200 units (1 uint = 1/72 inch)
                    media_box.x2 -= 200;

                    media_box.Update();

                    input_doc.Save(output_path + "tiger_shift.pdf", 0);
                }

                Console.WriteLine("Done. Result saved in tiger_shift...");
            }
            catch (PDFNetException e)
            {
                Console.WriteLine(e.Message);
            }
        }
Ejemplo n.º 2
0
        private List <LineFound> GetValue(PDFDoc doc, PdfString ricPosition, string patternRic, string patternValue)
        {
            List <LineFound> bulkFile = new List <LineFound>();

            try
            {
                List <string>    line = new List <string>();
                List <PdfString> ric  = null;

                //for (int i = 1; i < 10; i++)
                for (int i = 1; i < doc.GetPageCount(); i++)
                {
                    ric = pa.RegexExtractByPositionWithPage(doc, patternRic, i, ricPosition.Position);
                    foreach (var item in ric)
                    {
                        LineFound lineFound = new LineFound();
                        lineFound.Ric        = item.Words.ToString();
                        lineFound.Position   = item.Position;
                        lineFound.PageNumber = i;
                        lineFound.LineData   = pa.RegexExtractByPositionWithPage(doc, patternValue, i, item.Position, PositionRect.X2);
                        bulkFile.Add(lineFound);
                    }
                }
            }
            catch (Exception ex)
            {
                string msg = string.Format("\r\n	     ClassName:  {0}\r\n	     MethodName: {1}\r\n	     Message:    {2}",
                                           System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.ToString(),
                                           System.Reflection.MethodBase.GetCurrentMethod().Name,
                                           ex.Message);
                Logger.Log(msg, Logger.LogType.Error);
            }

            return(bulkFile);
        }
        private Bitmap renPdfToBitmap(CACodecTools caTool, string pageFile, byte[] key, int pg, int dpi, float scal, int decodedPageIndex, Border border, bool isSinglePage)
        {
            System.Drawing.Color white = System.Drawing.Color.White;
            Bitmap aBitmap             = null;

            try
            {
                if (decodedPDFPages[decodedPageIndex] == null)
                {
                    decodedPDFPages[decodedPageIndex] = caTool.fileAESDecode(pageFile, key);
                }
            }
            catch (Exception ex)
            {
                decodedPDFPages[decodedPageIndex] = null;
                LogTool.Debug(ex);
            }
            try
            {
                PDFDoc pDFDoc = new PDFDoc();
                pDFDoc.Init("PVD20-M4IRG-QYZK9-MNJ2U-DFTK1-MAJ4L", "PDFX3$Henry$300604_Allnuts#");
                pDFDoc.OpenFromMemory(decodedPDFPages[decodedPageIndex], (uint)decodedPDFPages[decodedPageIndex].Length, 0);
                PXCV_Lib36.PXV_CommonRenderParameters aCommonRenderParams = prepareCommonRenderParameter(pDFDoc, dpi, pg, scal, 0, 0, border, isSinglePage);
                pDFDoc.DrawPageToDIBSection(IntPtr.Zero, pg, white, aCommonRenderParams, out aBitmap);
                pDFDoc.ReleasePageCachedData(pg, 1);
                pDFDoc.Delete();
                return(aBitmap);
            }
            catch (Exception ex2)
            {
                LogTool.Debug(ex2);
                return(aBitmap);
            }
        }
        protected void AddTextDataToPdfPage(PDFDoc pdfDoc, pdftron.PDF.Page pdfPage, string text)
        {
            var elementWriter = new ElementWriter();

            try
            {
                elementWriter.Begin(pdfPage);

                var elementBuilder = new ElementBuilder();
                var textFont       = Font.Create(pdfDoc, Font.StandardType1Font.e_times_roman);
                var textFontSize   = 10.0;
                var textElement    = elementBuilder.CreateTextBegin(textFont, textFontSize);
                elementWriter.WriteElement(textElement);
                elementBuilder.CreateTextRun(text);
                elementWriter.WriteElement(textElement);
                var textEnd = elementBuilder.CreateTextEnd();
                elementWriter.WriteElement(textEnd);

                elementWriter.Flush();
                elementWriter.End();
            }
            finally
            {
                elementWriter.Dispose();
            }
        }
Ejemplo n.º 5
0
        public MainPageViewModel()
        {
            // Register commands
            CMDOpenFile   = new RelayCommand(OpenFile);
            CMDAddBarCode = new RelayCommand(AddBarcode);

            // Initialize PDFTron's SDK in demo mode
            pdftron.PDFNet.Initialize("");

            // Initialize PDF View Control
            PDFViewCtrl = new PDFViewCtrl();
            PDFViewCtrl.PointerPressed += PDFViewCtrl_PointerPressed;

            // Open getting started PDF file
            PDFDoc doc = new PDFDoc("Resources/GettingStarted.pdf");

            doc.InitSecurityHandler();

            // Load document into PDF View Control
            PDFViewCtrl.SetDoc(doc);

            // Init ToolManager
            toolManager = new ToolManager(PDFViewCtrl);

            // Init Dialog ViewModel
            barcodeViewModel = new BarcodeViewModel();
            BarcodeViewModel = new BarcodeDialogViewModel(new BarcodeDialogService(barcodeViewModel));
        }
Ejemplo n.º 6
0
        public void RunPdfTron(string input_path)
        {
            PDFNet.Initialize();

            // string output_path = "../../../../TestFiles/Output/";

            try
            {
                // Open the test file
                PDFDoc doc = new PDFDoc(input_path);
                doc.InitSecurityHandler();

                PageIterator  itr;
                ElementReader page_reader = new ElementReader();

                for (itr = doc.GetPageIterator(); itr.HasNext(); itr.Next())        //  Read every page
                {
                    int pageno = itr.GetPageNumber();


                    page_reader.Begin(itr.Current());
                    ProcessElements(page_reader);
                    page_reader.End();
                }

                page_reader.Dispose(); // Calling Dispose() on ElementReader/Writer/Builder can result in increased performance and lower memory consumption.
                doc.Close();
            }
            catch (PDFNetException e)
            {
                ConsoleLog += e.Message;
            }

            PDFNet.Terminate();
        }
        private void btnProtPdf_Click(object sender, EventArgs e)
        {
            if (ofdAbrirArquivo.ShowDialog() == DialogResult.OK)
            {
                using (PDFDoc doc = new PDFDoc(ofdAbrirArquivo.FileName))
                {
                    //Apply a new security handler with given security settings.
                    // In order to open saved PDF you will need a user password 'test'.
                    SecurityHandler new_handler = new SecurityHandler(SecurityHandler.AlgorithmType.e_AES_256);

                    // Set a new password required to open a document
                    string my_password = "******";
                    new_handler.ChangeUserPassword(my_password);

                    // Set Permissions
                    new_handler.SetPermission(SecurityHandler.Permission.e_print, true);
                    new_handler.SetPermission(SecurityHandler.Permission.e_extract_content, false);

                    // Note: document takes the ownership of new_handler.
                    doc.SetSecurityHandler(new_handler);

                    doc.Save(GetNewFileName(ofdAbrirArquivo.FileName, FileNameOptionEnum.Encrypt), SDFDoc.SaveOptions.e_linearized);
                }
            }
        }
Ejemplo n.º 8
0
        void CreateHighlight(PDFDoc pdfDoc, Page page, Rect rect)
        {
            var highLight = Highlight.Create(pdfDoc, rect);

            highLight.RefreshAppearance();
            page.AnnotPushBack(highLight);
        }
Ejemplo n.º 9
0
        // Creates some text and associate it with the text layer
        static Obj CreateGroup3(PDFDoc doc, Obj layer)
        {
            using (ElementWriter writer = new ElementWriter())
                using (ElementBuilder builder = new ElementBuilder())
                {
                    writer.Begin(doc);

                    // Begin writing a block of text
                    Element element = builder.CreateTextBegin(Font.Create(doc, Font.StandardType1Font.e_times_roman), 120);
                    writer.WriteElement(element);

                    element = builder.CreateTextRun("A text layer!");

                    // Rotate text 45 degrees, than translate 180 pts horizontally and 100 pts vertically.
                    Matrix2D transform = Matrix2D.RotationMatrix(-45 * (3.1415 / 180.0));
                    transform.Concat(1, 0, 0, 1, 180, 100);
                    element.SetTextMatrix(transform);

                    writer.WriteElement(element);
                    writer.WriteElement(builder.CreateTextEnd());

                    Obj grp_obj = writer.End();

                    // Indicate that this form (content group) belongs to the given layer (OCG).
                    grp_obj.PutName("Subtype", "Form");
                    grp_obj.Put("OC", layer);
                    grp_obj.PutRect("BBox", 0, 0, 1000, 1000);                  // Set the clip box for the content.

                    return(grp_obj);
                }
        }
Ejemplo n.º 10
0
        private Bitmap a(CACodecTools A_0, string A_1, byte[] A_2, int A_3, int A_4, float A_5, int A_6, Border A_7, bool A_8)
        {
            System.Drawing.Color white = System.Drawing.Color.White;
            Bitmap aBitmap             = null;

            try
            {
                if (decodedPDFPages[A_6] == null)
                {
                    decodedPDFPages[A_6] = A_0.fileAESDecode(A_1, A_2);
                }
            }
            catch (Exception ex)
            {
                decodedPDFPages[A_6] = null;
                throw ex;
            }
            try
            {
                PDFDoc pDFDoc = new PDFDoc();
                pDFDoc.Init("PVD20-M4IRG-QYZK9-MNJ2U-DFTK1-MAJ4L", "PDFX3$Henry$300604_Allnuts#");
                pDFDoc.OpenFromMemory(decodedPDFPages[A_6], (uint)decodedPDFPages[A_6].Length, 0);
                PXCV_Lib36.PXV_CommonRenderParameters aCommonRenderParams = a(pDFDoc, A_4, A_3, A_5, 0, 0, A_7, A_8);
                pDFDoc.DrawPageToDIBSection(IntPtr.Zero, A_3, white, aCommonRenderParams, out aBitmap);
                pDFDoc.ReleasePageCachedData(A_3, 1);
                pDFDoc.Delete();
                return(aBitmap);
            }
            catch (Exception ex2)
            {
                throw ex2;
            }
        }
Ejemplo n.º 11
0
        // NOTE: Overlay two PDF files and give the visual color diff between them
        // Used to review two document revisions or drawing blueprints that are overlayed with updated data
        private async void ProcessVisualDiff()
        {
            var docA = mPDFViewCtrlA.GetDoc();
            var docB = mPDFViewCtrlB.GetDoc();

            DiffOptions diffOptions = new DiffOptions();

            diffOptions.SetColorA(new ColorPt(1, 0, 0));
            diffOptions.SetColorB(new ColorPt(0, 0, 0));
            diffOptions.SetBlendMode(GStateBlendMode.e_bl_normal);

            pdftron.PDF.Page docAPage = docA.GetPage(1);
            pdftron.PDF.Page docBPage = docB.GetPage(1);

            try
            {
                PDFDoc outputDocument = new PDFDoc();
                outputDocument.AppendVisualDiff(docAPage, docBPage, diffOptions);

                Controls.PDFResultDialog contentDialog = new Controls.PDFResultDialog();
                var pdfCompare = new PDFCompareResult(outputDocument);
                pdfCompare.CloseButtonClicked += delegate
                {
                    contentDialog.Hide();
                };

                contentDialog.Content = pdfCompare;
                await contentDialog.ShowAsync();
            }
            catch (Exception ex)
            { }
        }
Ejemplo n.º 12
0
        public MainPageViewModel()
        {
            mPDFViewCtrlA = new PDFViewCtrl();
            mPDFViewCtrlB = new PDFViewCtrl();

            // Set control background color to gray
            mPDFViewCtrlA.SetBackgroundColor(Windows.UI.Color.FromArgb(100, 49, 51, 53));
            mPDFViewCtrlB.SetBackgroundColor(Windows.UI.Color.FromArgb(100, 49, 51, 53));

            // Setup commands
            CMDOpenPdfA          = new RelayCommand(OpenFileA);
            CMDOpenPdfB          = new RelayCommand(OpenFileB);
            CMDProcessTextDiff   = new RelayCommand(ProcessTextDiff);
            CMDProcessVisualDiff = new RelayCommand(ProcessVisualDiff);
            CMDSyncScroll        = new RelayCommand(SyncScroll);
            CMDOpenFileA         = new RelayCommand(OpenFileA);
            CMDOpenFileB         = new RelayCommand(OpenFileB);

            mPDFViewCtrlA.OnSetDoc += MPDFViewA_OnSetDoc;
            mPDFViewCtrlB.OnSetDoc += MPDFViewB_OnSetDoc;

            // Initialize PDFView with a PDF document to be displayed
            PDFDoc doc_a = new PDFDoc("Resources/GettingStarted_rev1.pdf");

            mPDFViewCtrlA.SetDoc(doc_a);
            PDFDoc doc_b = new PDFDoc("Resources/GettingStarted_rev2.pdf");

            mPDFViewCtrlB.SetDoc(doc_b);
        }
Ejemplo n.º 13
0
        static void Main(string[] args)
        {
            // Initialize PDFNet before using any PDFTron related
            // classes and methods (some exceptions can be found in API)
            PDFNet.Initialize();

            // Using PDFNet related classes and methods, must catch or throw PDFNetException
            try
            {
                using (PDFDoc doc = new PDFDoc())
                {
                    doc.InitSecurityHandler();

                    // An example of creating a new page and adding it to
                    // doc's sequence of pages
                    Page newPg = doc.PageCreate();
                    doc.PagePushBack(newPg);

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

                    System.Console.WriteLine("Done. Results saved in linearized_output.pdf");
                }
            }
            catch (PDFNetException e)
            {
                System.Console.WriteLine(e);
            }
        }
Ejemplo n.º 14
0
        private async Task <PDFDoc> OpenFilePDFViewer(IStorageFile file, FileAccessMode mode)
        {
            if (file == null)
            {
                return(null);
            }

            Windows.Storage.Streams.IRandomAccessStream stream;
            try
            {
                stream = await file.OpenAsync(mode);
            }
            catch (Exception e)
            {
                // NOTE: If file already opened it will cause an exception
                var msg = new MessageDialog(e.Message);
                _ = msg.ShowAsync();
                return(null);
            }

            PDFDoc doc = new PDFDoc(stream);

            doc.InitSecurityHandler();

            return(doc);
        }
Ejemplo n.º 15
0
        static void AddCovePage(PDFDoc doc)
        {
            // Here we dynamically generate cover page (please see ElementBuilder
            // sample for more extensive coverage of PDF creation API).
            Page page = doc.PageCreate(new Rect(0, 0, 200, 200));

            using (ElementBuilder b = new ElementBuilder())
                using (ElementWriter w = new ElementWriter())
                {
                    w.Begin(page);
                    Font font = Font.Create(doc, "Arial", "");
                    w.WriteElement(b.CreateTextBegin(font, 12));
                    Element e = b.CreateTextRun("My PDF Collection");
                    e.SetTextMatrix(1, 0, 0, 1, 50, 96);
                    e.GetGState().SetFillColorSpace(ColorSpace.CreateDeviceRGB());
                    e.GetGState().SetFillColor(new ColorPt(1, 0, 0));
                    w.WriteElement(e);
                    w.WriteElement(b.CreateTextEnd());
                    w.End();
                    doc.PagePushBack(page);
                }

            // Alternatively we could import a PDF page from a template PDF document
            // (for an example please see PDFPage sample project).
            // ...
        }
Ejemplo n.º 16
0
        static void ClearSignature(string in_docpath,
                                   string in_digsig_field_name,
                                   string in_outpath)
        {
            Console.Out.WriteLine("================================================================================");
            Console.Out.WriteLine("Clearing certification signature");

            using (PDFDoc doc = new PDFDoc(in_docpath))
            {
                DigitalSignatureField digsig = new DigitalSignatureField(doc.GetField(in_digsig_field_name));

                Console.Out.WriteLine("Clearing signature: " + in_digsig_field_name);
                digsig.ClearSignature();

                if (!digsig.HasCryptographicSignature())
                {
                    Console.Out.WriteLine("Cryptographic signature cleared properly.");
                }

                // Save incrementally so as to not invalidate other signatures' hashes from previous saves.
                doc.Save(in_outpath, SDFDoc.SaveOptions.e_incremental);
            }

            Console.Out.WriteLine("================================================================================");
        }
Ejemplo n.º 17
0
        static void SignPDF(string in_docpath,
                            string in_approval_field_name,
                            string in_private_key_file_path,
                            string in_keyfile_password,
                            string in_appearance_img_path,
                            string in_outpath)
        {
            Console.Out.WriteLine("================================================================================");
            Console.Out.WriteLine("Signing PDF document");

            // Open an existing PDF
            using (PDFDoc doc = new PDFDoc(in_docpath))
            {
                // Sign the approval signatures.
                Field found_approval_field = doc.GetField(in_approval_field_name);
                DigitalSignatureField found_approval_signature_digsig_field = new DigitalSignatureField(found_approval_field);
                Image           img2 = Image.Create(doc, in_appearance_img_path);
                SignatureWidget found_approval_signature_widget = new SignatureWidget(found_approval_field.GetSDFObj());
                found_approval_signature_widget.CreateSignatureAppearance(img2);

                        #if USE_DOTNET_CRYPTO
                DotNetCryptoSignatureHandler sigHandler   = new DotNetCryptoSignatureHandler(in_private_key_file_path, in_keyfile_password);
                SDF.SignatureHandlerId       sigHandlerId = doc.AddSignatureHandler(sigHandler);
                found_approval_signature_digsig_field.SignOnNextSaveWithCustomHandler(sigHandlerId);
                        #else
                found_approval_signature_digsig_field.SignOnNextSave(in_private_key_file_path, in_keyfile_password);
                        #endif

                doc.Save(in_outpath, SDFDoc.SaveOptions.e_incremental);
            }
            Console.Out.WriteLine("================================================================================");
        }
Ejemplo n.º 18
0
        public void GenerateImages_IfThumbnailDirectoriesDoesNotExist_CreatesDirectoriesByCountOfPages()
        {
            // Arrange
            const int pdfDocPageCount = 2;
            var       thumbnailPath   = string.Format("{0}{1}/", DummyImagePath, _thumbnailResolution);

            var createDirectoryCallCount = 0;

            ShimDirectory.ExistsString          = (directoryPath) => { return(false); };
            ShimDirectory.CreateDirectoryString = (directoryPath) =>
            {
                if (directoryPath == thumbnailPath)
                {
                    createDirectoryCallCount++;
                }
                return(null);
            };

            ShimPDFDraw.AllInstances.ExportPageStringStringObj = (_, __, ___, ____, _____) => { };

            using (var pdfDoc = new PDFDoc())
            {
                for (var i = 0; i < pdfDocPageCount; i++)
                {
                    pdfDoc.PagePushBack(pdfDoc.PageCreate());
                }

                // Act
                _testEntityPrivate.Invoke(GenerateImagesMethodName, pdfDoc);
            }

            // Assert
            createDirectoryCallCount.ShouldBe(pdfDocPageCount);
        }
        public FileItemDTO ProtectFile(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.Protect)
            };

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

            using (PDFDoc doc = new PDFDoc(fileItem.FileFullPath))
            {
                SecurityHandler new_handler = new SecurityHandler(SecurityHandler.AlgorithmType.e_AES_256);

                string my_password = "******";
                new_handler.ChangeUserPassword(my_password);

                new_handler.SetPermission(SecurityHandler.Permission.e_print, true);
                new_handler.SetPermission(SecurityHandler.Permission.e_extract_content, false);

                doc.SetSecurityHandler(new_handler);

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

            return(fileItemDTO);
        }
Ejemplo n.º 20
0
        public List <PdfString> RegexSearch(PDFDoc doc, string pattern, bool ifWholeWord, int startPage, int endPage, bool ignoreCase)
        {
            List <PdfString> result         = new List <PdfString>();
            Int32            page_num       = 0;
            string           result_str     = "";
            string           ambient_string = "";
            Highlights       hlts           = new Highlights();

            Int32 mode = (Int32)(TextSearch.SearchMode.e_reg_expression | TextSearch.SearchMode.e_highlight);

            if (ifWholeWord)
            {
                mode |= (Int32)TextSearch.SearchMode.e_whole_word;
            }
            if (ignoreCase)
            {
                mode |= (Int32)TextSearch.SearchMode.e_case_sensitive;
            }

            int pageCount = doc.GetPageCount();

            if (endPage > pageCount)
            {
                endPage = pageCount;
            }

            TextSearch txt_search = new TextSearch();

            txt_search.Begin(doc, pattern, mode, startPage, endPage);

            while (true)
            {
                TextSearch.ResultCode code = txt_search.Run(ref page_num, ref result_str, ref ambient_string, hlts);

                if (code == TextSearch.ResultCode.e_found)
                {
                    hlts.Begin(doc);
                    double[] box  = null;
                    string   temp = result_str;

                    while (hlts.HasNext())
                    {
                        box = hlts.GetCurrentQuads();
                        if (box.Length != 8)
                        {
                            hlts.Next();
                            continue;
                        }

                        result.Add(new PdfString(result_str, new Rect(box[0], box[1], box[4], box[5]), page_num));
                        hlts.Next();
                    }
                }
                else if (code == TextSearch.ResultCode.e_done)
                {
                    break;
                }
            }
            return(result);
        }
        public FileItemDTO CompressFile(FileItemEntity fileItem)
        {
            fileItem.FileFullPath = FileUtils.GetDefaultInputPath() + fileItem.FileName;

            File.WriteAllBytes(fileItem.FileFullPath, fileItem.Bytes);

            var fileItemDTO = new FileItemDTO()
            {
                Id           = fileItem.Id,
                FileFullPath = FileUtils.GetNewFileName(fileItem.FileName, FileNameOptionEnum.Compress)
            };

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

            using (PDFDoc in_doc = new PDFDoc(fileItem.FileFullPath))
            {
                Optimizer.Optimize(in_doc);

                using (PDFDoc doc = new PDFDoc())
                {
                    doc.InsertPages(doc.GetPageCount() + 1, in_doc, 1, in_doc.GetPageCount(), PDFDoc.InsertFlag.e_none);

                    in_doc.Save(fileItemDTO.FileFullPath, SDFDoc.SaveOptions.e_linearized);
                }
            }

            return(fileItemDTO);
        }
Ejemplo n.º 22
0
        static void Main(string[] args)
        {
            PDFNet.Initialize();

            try
            {
                using (PDFDoc doc = new PDFDoc(input_path + "numbered.pdf"))
                {
                    doc.InitSecurityHandler();

                    // An example of using SDF/Cos API to add any type of annotations.
                    AnnotationLowLevelAPI(doc);
                    doc.Save(output_path + "annotation_test1.pdf", SDFDoc.SaveOptions.e_linearized);
                    System.Console.WriteLine("Done. Results saved in annotation_test1.pdf");

                    // An example of using the high-level PDFNet API to read existing annotations,
                    // to edit existing annotations, and to create new annotation from scratch.
                    AnnotationHighLevelAPI(doc);
                    doc.Save(output_path + "annotation_test2.pdf", SDFDoc.SaveOptions.e_linearized);
                    System.Console.WriteLine("Done. Results saved in annotation_test2.pdf");
                }

                // an example of creating various annotations in a brand new document
                using (PDFDoc doc1 = new PDFDoc())
                {
                    CreateTestAnnots(doc1);
                    doc1.Save(output_path + "new_annot_test_api.pdf", SDFDoc.SaveOptions.e_linearized);
                    System.Console.WriteLine("Saved new_annot_test_api.pdf");
                }
            }
            catch (PDFNetException e)
            {
                System.Console.WriteLine(e.Message);
            }
        }
Ejemplo n.º 23
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();
            PDFNet.AddResourceSearchPath("../../../../../Lib/");
            if (!CADModule.IsModuleAvailable())
            {
                Console.WriteLine();
                Console.WriteLine("Unable to run CAD2PDFTest: PDFTron SDK CAD module not available.");
                Console.WriteLine("---------------------------------------------------------------");
                Console.WriteLine("The CAD module is an optional add-on, available for download");
                Console.WriteLine("at http://www.pdftron.com/. If you have already downloaded this");
                Console.WriteLine("module, ensure that the SDK is able to find the required files");
                Console.WriteLine("using the PDFNet::AddResourceSearchPath() function.");
                Console.WriteLine();
            }

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

            string input_file_name  = "construction drawings color-28.05.18.dwg";
            string output_file_name = "construction drawings color-28.05.18.pdf";

            if (args.Length != 0)
            {
                input_file_name  = args[0];
                output_file_name = input_file_name + ".pdf";
            }

            Console.WriteLine("Example cad:");
            try
            {
                using (PDFDoc pdfdoc = new PDFDoc())
                {
                    if (IsRVTFile(input_file_name))
                    {
                        CADConvertOptions opts = new CADConvertOptions();
                        opts.SetPageWidth(800);
                        opts.SetPageHeight(600);
                        opts.SetRasterDPI(150);

                        pdftron.PDF.Convert.FromCAD(pdfdoc, input_path + input_file_name, opts);
                    }
                    else
                    {
                        pdftron.PDF.Convert.FromCAD(pdfdoc, input_path + input_file_name, null);
                    }
                    pdfdoc.Save(output_path + output_file_name, SDFDoc.SaveOptions.e_remove_unused);
                }

                Console.WriteLine("Done.");
            }
            catch (PDFNetException e)
            {
                Console.WriteLine(e.Message);
            }
        }
Ejemplo n.º 24
0
        static void Main(string[] args)
        {
            PDFNet.Initialize();

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

            try
            {
                Console.WriteLine("-------------------------------------------------");
                Console.WriteLine("Sample 1 - Extract text data from all pages in the document.");

                // Open the test file
                Console.WriteLine("Opening the input pdf...");
                using (PDFDoc doc = new PDFDoc(input_path + "newsletter.pdf"))
                    using (ElementReader page_reader = new ElementReader())
                    {
                        doc.InitSecurityHandler();

                        PageIterator itr;
                        for (itr = doc.GetPageIterator(); itr.HasNext(); itr.Next())                            //  Read every page
                        {
                            page_reader.Begin(itr.Current());
                            ProcessElements(page_reader);
                            page_reader.End();
                        }
                        Console.WriteLine("Done.");
                    }
            }
            catch (PDFNetException e)
            {
                Console.WriteLine(e.Message);
            }
        }
        public async Task ConvertOfficeFile(string inFilePath, string outFilePath)
        {
            string errText = "NONE";

            try
            {
                PDFDoc pdfDoc = new PDFDoc();

                OfficeToPDFOptions options = null;
                //string pathToPdfTronFontResources = "C:\\Users\\hliao\\Documents\\Github\\FieldMobileApp\\App\\Field.Mobile\\Field.Mobile.Droid\\obj\\Debug\\100\\designtime\\Resource.designer.cs";
                //options.SetLayoutResourcesPluginPath(pathToPdfTronFontResources);

                pdftron.PDF.Convert.OfficeToPDF(pdfDoc, inFilePath, options);
                await pdfDoc.SaveAsync(outFilePath, SDFDocSaveOptions.e_remove_unused);
            }
            catch (Exception ex)
            {
                pdftron.Common.PDFNetException pdfNetEx = new pdftron.Common.PDFNetException(ex.HResult);
                if (pdfNetEx.IsPDFNetException)
                {
                    errText  = string.Format("Exeption at line {0} in file {1}", pdfNetEx.LineNumber, pdfNetEx.FileName);
                    errText += Environment.NewLine;
                    errText += string.Format("Message: {0}", pdfNetEx.Message);
                }
                else
                {
                    errText = ex.ToString();
                }
            }
            if (!errText.Equals("NONE"))
            {
                //look at the error text
                var x = errText;
            }
        }
        private void btnNovoPdf_Click(object sender, System.EventArgs e)
        {
            // Using PDFNet related classes and methods, must
            // catch or throw PDFNetException
            try
            {
                using (PDFDoc doc = new PDFDoc())
                {
                    using (Stamper s = new Stamper(Stamper.SizeType.e_relative_scale, 0.5, 0.5))
                    {
                        var randomNumber = new Random().Next(0, System.Convert.ToInt32(tbxNumMaxArquivos.Text));
                        doc.InitSecurityHandler();

                        // An example of creating a new page and adding it to
                        // doc's sequence of pages
                        Page newPg = doc.PageCreate();
                        doc.PagePushBack(newPg);

                        s.SetAlignment(Stamper.HorizontalAlignment.e_horizontal_center, Stamper.VerticalAlignment.e_vertical_center);
                        s.SetFontColor(new ColorPt(1, 0, 0)); // set text color to red
                        s.StampText(doc, $"{tbxDefaultNewName.Text} document {randomNumber}", new PageSet(1, doc.GetPageCount()));

                        var caminhoDestino = chkGerarWatchFolder.Checked ? CONVERTER_DEFAULT_OUTPUT_PATH : fbdCaminhoPasta.SelectedPath;

                        // Save as a linearized file which is most popular
                        // and effective format for quick PDF Viewing.
                        doc.Save(caminhoDestino + $"\\{tbxDefaultNewName.Text}_{randomNumber}.pdf", SDFDoc.SaveOptions.e_linearized);
                    }
                }
            }
            catch (PDFNetException ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Ejemplo n.º 27
0
        public void GetPageDetails_IfPdfDocHasThreePages_ThreePagesAddedIntoObjectEdition()
        {
            // Arrange
            var pdfDoc = new PDFDoc();

            try
            {
                var pdfPage01 = pdfDoc.PageCreate();
                var pdfPage02 = pdfDoc.PageCreate();
                var pdfPage03 = pdfDoc.PageCreate();

                pdfDoc.PagePushBack(pdfPage01);
                pdfDoc.PagePushBack(pdfPage02);
                pdfDoc.PagePushBack(pdfPage03);

                // Act
                _testEntityPrivate.Invoke(GetPageDetailsMethodName, pdfDoc);
            }
            finally
            {
                pdfDoc.Dispose();
            }

            // Assert
            _objectEdition.PageCollection.Count.ShouldBe(3);
        }
Ejemplo n.º 28
0
        public void GetPageDetails_IfPdfDocHasPage_SetsObjectEditionPageProperties()
        {
            // Arrange
            const int page01Index     = 0;
            const int pdfPage01Number = 1;
            var       pdfDoc          = new PDFDoc();

            int pdfPage01Width, pdfPage01Height;

            try
            {
                var pdfPage01 = pdfDoc.PageCreate();
                pdfPage01Width  = (int)pdfPage01.GetPageWidth();
                pdfPage01Height = (int)pdfPage01.GetPageHeight();
                pdfDoc.PagePushBack(pdfPage01);
                AddTextDataToPdfPage(pdfDoc, pdfPage01, PdfPageText);

                // Act
                _testEntityPrivate.Invoke(GetPageDetailsMethodName, pdfDoc);
            }
            finally
            {
                pdfDoc.Dispose();
            }

            // Assert
            var page01 = _objectEdition.PageCollection[page01Index];

            page01.PageNo.ShouldBe(pdfPage01Number);
            page01.DisplayNo.ShouldBe(pdfPage01Number.ToString());
            page01.TextContent.ShouldBe(PdfPageText);
            page01.Width.ShouldBe(pdfPage01Width);
            page01.Height.ShouldBe(pdfPage01Height);
        }
Ejemplo n.º 29
0
        public void GenerateImages_WhenCalled_GeneratesPageThumbnails()
        {
            // Arrange
            const int pdfDocPageCount = 2;
            var       thumbnailPath   = string.Format("{0}{1}/", DummyImagePath, _thumbnailResolution);

            ShimDirectory.ExistsString          = (directoryPath) => { return(true); };
            ShimDirectory.CreateDirectoryString = (directoryPath) => { return(null); };

            var exportCallCount = 0;

            ShimPDFDraw.AllInstances.ExportPageStringStringObj = (pdfDraw, pdfPage, fileName, fileFormat, encoderHints) =>
            {
                if (fileName.StartsWith(thumbnailPath, StringComparison.OrdinalIgnoreCase) &&
                    fileFormat.Equals("png", StringComparison.OrdinalIgnoreCase))
                {
                    exportCallCount++;
                }
            };

            using (var pdfDoc = new PDFDoc())
            {
                for (var i = 0; i < pdfDocPageCount; i++)
                {
                    pdfDoc.PagePushBack(pdfDoc.PageCreate());
                }

                // Act
                _testEntityPrivate.Invoke(GenerateImagesMethodName, pdfDoc);
            }

            // Assert
            exportCallCount.ShouldBe(pdfDocPageCount);
        }
Ejemplo n.º 30
0
        async private void OpenFile()
        {
            FileOpenPicker filePicker = new FileOpenPicker();

            filePicker.ViewMode = PickerViewMode.List;
            filePicker.FileTypeFilter.Add(".pdf");

            StorageFile file = await filePicker.PickSingleFileAsync();

            if (file == null)
            {
                return;
            }

            Windows.Storage.Streams.IRandomAccessStream stream;
            try
            {
                stream = await file.OpenAsync(FileAccessMode.ReadWrite);
            }
            catch (Exception e)
            {
                // NOTE: If file already opened it will cause an exception
                var msg = new MessageDialog(e.Message);
                _ = msg.ShowAsync();
                return;
            }

            PDFDoc doc = new PDFDoc(stream);

            doc.InitSecurityHandler();

            // Set loaded doc to PDFView Controler
            PDFViewCtrl.SetDoc(doc);
        }
Ejemplo n.º 31
0
 public PdfBookReader(PDFDoc book)
 {
     PDFNet.Initialize();
     pdftron.PDFNet.SetViewerCache(100 * 1024 * 1024, true);
     _book = book;
     m_draw = new PDFDraw();
 }
        //// 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;
        }
        // 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);
            }
        }
        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/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;
            }
        }
        // GET: api/SeparatePDF/5
        public HttpResponseMessage Get(string id)
        //public string Get(string id)
        {
            id = id + ",";
            PDFNet.Initialize("CT Orthopaedic Specialists(ct-ortho.com):ENTCPU:1::W:AMS(20160714):DF4FD2223CBF58B9128E100F400DD2BC2BFD701DC22C3C2E6D83F6B6F5C7");
            PDFDoc newDocument = new PDFDoc();
            string[] pagesSeparationGroups = id.Split(',');
            string[] newPDFNames = new string[pagesSeparationGroups.Length - 1];
            PDFDoc[] NewPDFDocs = new PDFDoc[pagesSeparationGroups.Length - 1];
            //string pathToCurrentPdfFile = documentData.GetCurrentDocumentPathPDF(Utility.GetUserName());

            for (int i = 0; i < newPDFNames.Length; i++)
            {
                newPDFNames[i] = Guid.NewGuid().ToString() + ".pdf";
                NewPDFDocs[i] = new PDFDoc();
            }

            DocumentRepository documentData = new DocumentRepository();
            //int pageCount = 0;

            CurrentDocuments currentDocuments = documentData.GetCurrentDocumentPathPDF(Utility.GetUserName());
            string pathToCurrentPdfFile = currentDocuments.PathToCurrentPDFDocument;

            //string[] fileName = pathToCurrentPdfFile.Split('\\');

            //File.Move(pathToCurrentPdfFile, ConfigurationValues.TemporaryFaxPath + "\\" + pathToCurrentPdfFile[pathToCurrentPdfFile.Length - 1]);
            PDFDoc separatePagesFromDocument = new PDFDoc(pathToCurrentPdfFile);

            for (int i = 0; i < pagesSeparationGroups.Length - 1; i++)
            {
                string[] pagesSeparation = pagesSeparationGroups[i].Split('-');

                //PageIterator itr = separatePagesFromDocument.GetPageIterator(i);
                NewPDFDocs[i].InsertPages(0, separatePagesFromDocument, int.Parse(pagesSeparation[0]), int.Parse(pagesSeparation[1]), PDFDoc.InsertFlag.e_none);
                NewPDFDocs[i].Save(ConfigurationValues.OutboundFaxDirectory + "\\" + Utility.GetUserName() + "\\" + newPDFNames[i], 0);
            }

            //            string pathToCurrentPdfFileTemp = pathToCurrentPdfFile.Replace(".pdf", "temp.pdf");
            //string pathToCurrentXodFile = documentData.GetCurrentDocumentPathXOD(Utility.GetUserName());
            separatePagesFromDocument.Close();
            separatePagesFromDocument.Dispose();
            File.Delete(pathToCurrentPdfFile);


            for (int i = 0; i < newPDFNames.Length; i++)
            {
                NewPDFDocs[i].Close();
                NewPDFDocs[i].Dispose();
            }

            string[] deleteTheDocumentList = currentDocuments.CurrentDocumentList.Split('~');
            for (int i = 0; i < deleteTheDocumentList.Length - 1; i++)
            {
                File.Delete(ConfigurationValues.OutboundFaxDirectory + "\\" + Utility.GetUserName() + "\\" + deleteTheDocumentList[i]);
            }
           // ConfigurationValues.OutboundFaxDirectory + "\\" + Utility.GetUserName() + "\\"


            HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
            return result;
        }
        // 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;
            }
        }
        // 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;
        }
        private void button1_Click(object sender, EventArgs e)
        {

            Utility.MergeTwoPDFDocuments("D:\\temp2\\Document1.pdf", "D:\\temp2\\Document2.pdf");

            PDFNet.Initialize("CT Orthopaedic Specialists(ct-ortho.com):ENTCPU:1::W:AMS(20160714):DF4FD2223CBF58B9128E100F400DD2BC2BFD701DC22C3C2E6D83F6B6F5C7");
            PDFDoc documentToAdd = new PDFDoc();

            pdftron.PDF.Convert.ToXod("C:\\4\\signature.pdf", "C:\\4\\signature.xod");

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

            //    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;
            //}

        }
Ejemplo n.º 41
0
        /// <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");
        }
        // GET: api/SeparatePDF/5
        public IHttpActionResult Get(string id)
        {
            try
            {

                id = id + ",";

                PDFNet.Initialize(ConfigurationValues.PdfTronLicenseKey);
                string[] pagesSeparationGroups = id.Split('~');
                string[] newPdfNames = new string[pagesSeparationGroups.Length - 1];
                PDFDoc[] newPdfDocs = new PDFDoc[pagesSeparationGroups.Length - 1];

                for (int i = 0; i < newPdfNames.Length; i++)
                {
                    newPdfNames[i] = Guid.NewGuid().ToString() + ".pdf";
                    newPdfDocs[i] = new PDFDoc();
                }

                DocumentRepository documentData = new DocumentRepository();

                CurrentDocuments currentDocuments = documentData.GetCurrentDocumentPathPdf(Utility.GetUserName());
                string[] currentDocumentCount = currentDocuments.CurrentDocumentList.Split('~');
                string[] currentDocumentList = currentDocumentCount[0].Split('\\');

                string pathToCurrentPdfFile = currentDocuments.PathToCurrentPdfDocument;

                string currentPdfPath = currentDocumentCount[0].Replace(currentDocumentList[currentDocumentList.Length - 1], "");

                PDFDoc separatePagesFromDocument = new PDFDoc(pathToCurrentPdfFile);

                for (int i = 0; i < pagesSeparationGroups.Length - 1; i++)
                {
                    string[] beginEndPageValues = pagesSeparationGroups[i].Split(',');

                    string pagesSeparationBegin = beginEndPageValues[0];
                    string pagesSeparationEnd = beginEndPageValues[1];

                    if (pagesSeparationBegin.Length > 0)
                    {
                        newPdfDocs[i].InsertPages(0, separatePagesFromDocument, int.Parse(pagesSeparationBegin), int.Parse(pagesSeparationEnd), PDFDoc.InsertFlag.e_none);
                        //newPdfDocs[i].Save(ConfigurationValues.OutboundFaxDirectory + "\\" + Utility.GetUserName() + "\\" + newPdfNames[i], 0);
                        newPdfDocs[i].Save(currentPdfPath + newPdfNames[i], 0);
                    }
                }

                separatePagesFromDocument.Close();
                separatePagesFromDocument.Dispose();
                File.Delete(currentDocumentCount[0]);


                for (int i = 0; i < newPdfNames.Length; i++)
                {
                    newPdfDocs[i].Close();
                    newPdfDocs[i].Dispose();
                }

                string[] deleteTheDocumentList = currentDocuments.CurrentDocumentList.Split('~');
                for (int i = 0; i < deleteTheDocumentList.Length - 1; i++)
                {
                    try
                    {
                        File.Delete(ConfigurationValues.OutboundFaxDirectory + "\\" + Utility.GetUserName() + "\\" + deleteTheDocumentList[i]);
                    }
                    catch { }
                }
                // ConfigurationValues.OutboundFaxDirectory + "\\" + Utility.GetUserName() + "\\"
                return Ok();
            }
            catch
            {
                return BadRequest("Error in splitting document.  Please try again");
            }
        }