public static void Run(
            String openPath,                    // source PDF document
            String savePath,                    // output PDF document
            String configPath                   // configuration file
            )
        {
            Pdfix pdfix = PdfixEngine.Instance;

            // open the document
            var doc = pdfix.OpenDoc(openPath, "");

            if (doc == null)
            {
                throw new Exception(pdfix.GetError());
            }

            using (var stm = pdfix.CreateFileStream(configPath, PsFileMode.kPsReadOnly))
            {
                var doc_prelight = doc.GetTemplate();
                if (doc_prelight == null)
                {
                    throw new Exception(pdfix.GetError());
                }
                doc_prelight.LoadFromStream(stm, PsDataFormat.kDataFormatJson);
            }

            // define a cancel progress callback
            PdfCancelDelegate cancel_callback = (data) =>
            {
                // to cancel the process return 1
                Console.WriteLine("PdfCancelProc callback was called");
                return(0);
            };

            if (!doc.RemoveTags(cancel_callback, null))
            {
                throw new Exception(pdfix.GetError());
            }

            if (!doc.AddTags(cancel_callback, null))
            {
                throw new Exception(pdfix.GetError());
            }

            if (!doc.Save(savePath, Pdfix.kSaveFull))
            {
                throw new Exception(pdfix.GetError());
            }

            doc.Close();
        }
        public static void Run(
            String openPath,                            // source PDF document
            String configPath,                          // configuration file
            bool preflight                              // create document preflight
            )
        {
            Pdfix pdfix = PdfixEngine.Instance;

            PdfDoc doc = pdfix.OpenDoc(openPath, "");

            if (doc == null)
            {
                throw new Exception(pdfix.GetError());
            }

            var docTemplate = doc.GetTemplate();

            if (docTemplate == null)
            {
                throw new Exception(pdfix.GetError());
            }

            // load config if set
            if (configPath.Length > 0)
            {
                var stm = pdfix.CreateFileStream(configPath, PsFileMode.kPsReadOnly);
                if (stm != null)
                {
                    if (!docTemplate.LoadFromStream(stm, PsDataFormat.kDataFormatJson))
                    {
                        throw new Exception(pdfix.GetError());
                    }
                    stm.Destroy();
                }
            }

            if (preflight)
            {
                for (var i = 0; i < doc.GetNumPages(); i++)
                {
                    if (!docTemplate.AddPage(i, null, null))
                    {
                        throw new Exception(pdfix.GetError());
                    }
                }
                if (docTemplate.Update(null, null))
                {
                    throw new Exception(pdfix.GetError());
                }
            }

            // prepare the output JSON
            var docObj = new JObject();

            var dataType = new DataType();

            dataType.page_annots  = true;
            dataType.extract_bbox = true;

            ExtractDocumentData(doc, docObj, dataType);

            doc.Close();

            Console.Write(docObj.ToString());
        }
Beispiel #3
0
        public async Task <List <string> > ExtractImage(
            String email,
            String licenseKey,
            String openPath,
            String imgPath,
            Double zoom
            )
        {
            List <string> imageList = new List <string>();

            try
            {
                Pdfix pdfix = new Pdfix();
                if (pdfix == null)
                {
                    throw new Exception("Pdfix initialization fail");
                }
                if (!pdfix.Authorize(email, licenseKey))
                {
                    throw new Exception(pdfix.GetError());
                }

                PdfDoc doc = pdfix.OpenDoc(openPath, "");
                if (doc == null)
                {
                    throw new Exception(pdfix.GetError());
                }

                for (int i = 0; i < doc.GetNumPages(); i++)
                {
                    PdfPage page = doc.AcquirePage(i);
                    if (page == null)
                    {
                        throw new Exception(pdfix.GetError());
                    }

                    PdfPageView pageView = page.AcquirePageView(zoom, PdfRotate.kRotate0);
                    if (pageView == null)
                    {
                        throw new Exception(pdfix.GetError());
                    }

                    int width  = pageView.GetDeviceWidth();
                    int height = pageView.GetDeviceHeight();

                    PsImage image = pdfix.CreateImage(width, height,
                                                      PsImageDIBFormat.kImageDIBFormatArgb);
                    if (image == null)
                    {
                        throw new Exception(pdfix.GetError());
                    }

                    PdfPageRenderParams pdfPageRenderParams = new PdfPageRenderParams();
                    pdfPageRenderParams.image  = image;
                    pdfPageRenderParams.matrix = pageView.GetDeviceMatrix();

                    pdfPageRenderParams.render_flags = Pdfix.kRenderAnnot;

                    if (!page.DrawContent(pdfPageRenderParams, null, IntPtr.Zero))
                    {
                        throw new Exception(pdfix.GetError());
                    }

                    PsStream stream = pdfix.CreateFileStream(imgPath + i.ToString() + ".jpg", PsFileMode.kPsWrite);

                    PdfImageParams imgParams = new PdfImageParams();
                    imgParams.format  = PdfImageFormat.kImageFormatJpg;
                    imgParams.quality = 75;

                    if (!image.SaveToStream(stream, imgParams))
                    {
                        throw new Exception(pdfix.GetError());
                    }

                    imageList.Add(imgPath + i.ToString());

                    stream.Destroy();

                    pageView.Release();
                    page.Release();
                }
                doc.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return(imageList);
        }
Beispiel #4
0
        public static void Run(
            String email,                               // authorization email
            String licenseKey,                          // authorization license key
            String openPath,                            // source PDF document
            String savePath,                            // output PDF document
            String configPath,                          // configuration file
            PdfHtmlParams htmlParams                    // html conversion params
            )
        {
            Pdfix pdfix = new Pdfix();

            if (pdfix == null)
            {
                throw new Exception("Pdfix initialization fail");
            }

            if (!pdfix.Authorize(email, licenseKey))
            {
                throw new Exception(pdfix.GetError());
            }

            PdfToHtml pdfToHtml = new PdfToHtml();

            if (pdfToHtml == null)
            {
                throw new Exception("PdfToHtml initialization fail");
            }

            if (!pdfToHtml.Initialize(pdfix))
            {
                throw new Exception(pdfix.GetError());
            }

            PdfDoc doc = pdfix.OpenDoc(openPath, "");

            if (doc == null)
            {
                throw new Exception(pdfix.GetError());
            }

            // customize conversion
            PsFileStream stm = pdfix.CreateFileStream(configPath, PsFileMode.kPsReadOnly);

            if (stm != null)
            {
                PdfDocTemplate docTmpl = doc.GetDocTemplate();
                if (docTmpl == null)
                {
                    throw new Exception(pdfix.GetError());
                }
                if (!docTmpl.LoadFromStream(stm, PsDataFormat.kDataFormatJson))
                {
                    throw new Exception(pdfix.GetError());
                }
                stm.Destroy();
            }

            // set html conversion params
            //htmlParams.type = PdfHtmlType.kPdfHtmlResponsive;
            //htmlParams.width = 1200;
            //htmlParams.flags |= PdfToHtml.kHtmlExportJavaScripts;
            //htmlParams.flags |= PdfToHtml.kHtmlExportFonts;
            //htmlParams.flags |= PdfToHtml.kHtmlRetainFontSize;
            //htmlParams.flags |= PdfToHtml.kHtmlRetainTextColor;
            htmlParams.flags |= PdfToHtml.kHtmlNoExternalCSS | PdfToHtml.kHtmlNoExternalJS |
                                PdfToHtml.kHtmlNoExternalIMG | PdfToHtml.kHtmlNoExternalFONT;

            PdfHtmlDoc htmlDoc = pdfToHtml.OpenHtmlDoc(doc);

            if (htmlDoc == null)
            {
                throw new Exception(pdfix.GetError());
            }

            if (!htmlDoc.Save(savePath, htmlParams, null, IntPtr.Zero))
            {
                throw new Exception(pdfix.GetError());
            }

            htmlDoc.Close();
            doc.Close();
            pdfToHtml.Destroy();
            pdfix.Destroy();
        }
Beispiel #5
0
        public static void Run(String open_file)
        {
            Pdfix pdfix = PdfixEngine.Instance;

            // open doc using file stream
            var fileStm = pdfix.CreateFileStream(open_file, PsFileMode.kPsReadOnly);

            if (fileStm == null)
            {
                throw new Exception(pdfix.GetError());
            }

            PdfDoc doc0 = pdfix.OpenDocFromStream(fileStm, "");

            if (doc0 == null)
            {
                throw new Exception(pdfix.GetError());
            }
            Console.WriteLine(@"Document open from file stream: {0} pages", doc0.GetNumPages());
            doc0.Close();

            // open doc using memory stream
            byte[] fileData = new byte[fileStm.GetSize()];
            fileStm.Read(0, fileData);

            var memStm = pdfix.CreateMemStream();

            memStm.Write(0, fileData);

            PdfDoc doc1 = pdfix.OpenDocFromStream(memStm, "");

            if (doc1 == null)
            {
                throw new Exception(pdfix.GetError());
            }
            Console.WriteLine(@"Document open from memory stream: {0} pages", doc1.GetNumPages());
            doc1.Close();
            memStm.Destroy();

            // open doc using custom stream
            PsStreamReadProc read_proc = (offset, buffer, size, client_data) =>
            {
                // read byte[] data from the source and copy to buffer
                var    stm = (((GCHandle)client_data).Target as PsStream);
                byte[] buf = new byte[size];
                var    ret = stm.Read(offset, buf);
                if (!ret)
                {
                    return(-1);
                }
                Marshal.Copy(buf, 0, buffer, size);
                return(size);
            };
            PsStreamGetSizeProc get_size_proc = (client_data) =>
            {
                // return the size of stream
                var stm = (((GCHandle)client_data).Target as PsStream);
                return(stm.GetSize());
            };

            var client_data_handle = GCHandle.Alloc(fileStm);
            var customStm          = pdfix.CreateCustomStream(read_proc, (IntPtr)client_data_handle);

            customStm.SetGetSizeProc(get_size_proc);

            PdfDoc doc2 = pdfix.OpenDocFromStream(customStm, "");

            if (doc2 == null)
            {
                throw new Exception(pdfix.GetError());
            }
            Console.WriteLine(@"Document open from custom stream: {0} pages", doc2.GetNumPages());
            doc2.Close();
            customStm.Destroy();
            client_data_handle.Free();

            fileStm.Destroy();
        }
Beispiel #6
0
        public static void Run(
            String openPath,                            // source PDF document
            String savePath                             // output image document
            )
        {
            Pdfix pdfix = PdfixEngine.Instance;

            PdfDoc doc = pdfix.OpenDoc(openPath, "");

            if (doc == null)
            {
                throw new Exception(pdfix.GetError());
            }

            // choose page to render
            var page = doc.AcquirePage(0);

            if (page == null)
            {
                throw new Exception(pdfix.GetError());
            }

            // prepare page view with zoom and rotation
            var pageView = page.AcquirePageView((float)1.0, PdfRotate.kRotate0);

            if (pageView == null)
            {
                throw new Exception(pdfix.GetError());
            }

            // prepare an image to write data into
            var image = pdfix.CreateImage(pageView.GetDeviceWidth(), pageView.GetDeviceHeight(),
                                          PsImageDIBFormat.kImageDIBFormatArgb);

            if (image == null)
            {
                throw new Exception(pdfix.GetError());
            }

            // draw content into the image
            if (!page.DrawContent(new PdfPageRenderParams()
            {
                clip_box = page.GetCropBox(),
                matrix = pageView.GetDeviceMatrix(),
                image = image
            },
                                  null, null))
            {
                throw new Exception(pdfix.GetError());
            }

            // prepare file stream to write into
            var stm = pdfix.CreateFileStream(savePath, PsFileMode.kPsTruncate);

            if (stm == null)
            {
                throw new Exception(pdfix.GetError());
            }

            // save image to file
            if (!image.SaveToStream(stm, new PdfImageParams()
            {
                format = PdfImageFormat.kImageFormatJpg,
                quality = 80
            }))
            {
                throw new Exception(pdfix.GetError());
            }

            // cleanup
            stm.Destroy();
            page.Release();
            doc.Close();
        }
        public static void Run(
            String openPath,                            // source PDF document
            String savePath,                            // output PDF document
            String configPath,                          // configuration file
            PdfHtmlParams htmlParams                    // html conversion params
            )
        {
            Pdfix pdfix = PdfixEngine.Instance;

            PdfDoc doc = pdfix.OpenDoc(openPath, "");

            if (doc == null)
            {
                throw new Exception(pdfix.GetError());
            }

            var html_conv = doc.CreateHtmlConversion();

            if (html_conv == null)
            {
                throw new Exception(pdfix.GetError());
            }

            // customize conversion
            PsFileStream stm = pdfix.CreateFileStream(configPath, PsFileMode.kPsReadOnly);

            if (stm != null)
            {
                var doc_prelight = doc.GetTemplate();
                if (doc_prelight == null)
                {
                    throw new Exception(pdfix.GetError());
                }
                if (!doc_prelight.LoadFromStream(stm, PsDataFormat.kDataFormatJson))
                {
                    throw new Exception(pdfix.GetError());
                }
                stm.Destroy();
            }

            // set html conversion params
            //htmlParams.type = PdfHtmlType.kPdfHtmlResponsive;
            //htmlParams.width = 1200;
            //htmlParams.flags |= Pdfix.kHtmlExportJavaScripts;
            //htmlParams.flags |= Pdfix.kHtmlExportFonts;
            //htmlParams.flags |= Pdfix.kHtmlRetainFontSize;
            //htmlParams.flags |= Pdfix.kHtmlRetainTextColor;
            htmlParams.flags |= Pdfix.kHtmlNoExternalCSS | Pdfix.kHtmlNoExternalJS |
                                Pdfix.kHtmlNoExternalIMG | Pdfix.kHtmlNoExternalFONT;
            htmlParams.image_params.format = PdfImageFormat.kImageFormatJpg;

            if (!html_conv.SetParams(htmlParams))
            {
                throw new Exception(pdfix.GetError());
            }

            if (!html_conv.Save(savePath, null, IntPtr.Zero))
            {
                throw new Exception(pdfix.GetError());
            }

            html_conv.Destroy();
            doc.Close();
        }
        public static void Run(
            String email,                       // authorization email
            String licenseKey,                  // authorization license key
            String openPath,                    // source PDF document
            String savePath,                    // output PDF document
            String configPath                   // configuration file
            )
        {
            Pdfix pdfix = new Pdfix();

            if (pdfix == null)
            {
                throw new Exception("Pdfix initialization fail");
            }

            if (!pdfix.Authorize(email, licenseKey))
            {
                throw new Exception(pdfix.GetError());
            }

            PdfDoc doc = pdfix.OpenDoc(openPath, "");

            if (doc == null)
            {
                throw new Exception(pdfix.GetError());
            }

            PsFileStream stm = pdfix.CreateFileStream(configPath, PsFileMode.kPsReadOnly);

            if (stm != null)
            {
                PdfDocTemplate docTmpl = doc.GetDocTemplate();
                if (docTmpl == null)
                {
                    throw new Exception(pdfix.GetError());
                }
                docTmpl.LoadFromStream(stm, PsDataFormat.kDataFormatJson);
                stm.Destroy();
            }

            // define a cancel progress callback
            PdfCancelProc cancel_callback = (data) =>
            {
                // to cancel the process return 1
                Console.WriteLine("PdfCancelProc callback was called");
                return(0);
            };

            PdfPage    page    = doc.AcquirePage(0);
            PdePageMap pageMap = page.AcquirePageMap(null, IntPtr.Zero);

            // define an event callback
            PdfEventProc event_callback = (data) =>
            {
                Console.WriteLine("Page contents did change. Releasing pageMap...");
                if (pageMap != null)
                {
                    pageMap.Release();
                    pageMap = null;
                }
            };

            if (!pdfix.RegisterEvent(PdfEventType.kEventPageContentsDidChange, event_callback, IntPtr.Zero))
            {
                throw new Exception(pdfix.GetError());
            }

            if (!doc.AddTags(cancel_callback, IntPtr.Zero))
            {
                throw new Exception(pdfix.GetError());
            }

            if (!doc.Save(savePath, PdfSaveFlags.kSaveFull))
            {
                throw new Exception(pdfix.GetError());
            }

            doc.Close();
            pdfix.Destroy();
        }
Beispiel #9
0
        public static void Run(
            String openPath,                    // source PDF document
            String configPath
            )
        {
            Pdfix pdfix = PdfixEngine.Instance;

            PdfDoc doc = pdfix.OpenDoc(openPath, "");

            if (doc == null)
            {
                throw new Exception(pdfix.GetError());
            }

            var doc_preflight = doc.GetTemplate();

            if (doc_preflight == null)
            {
                throw new Exception(pdfix.GetError());
            }

            // load user-defined confguration
            PsFileStream stm = pdfix.CreateFileStream(configPath, PsFileMode.kPsReadOnly);

            if (stm != null)
            {
                var doc_prelight = doc.GetTemplate();
                if (doc_prelight == null)
                {
                    throw new Exception(pdfix.GetError());
                }
                doc_prelight.LoadFromStream(stm, PsDataFormat.kDataFormatJson);
                stm.Destroy();
            }

            // add reference pages to preflight
            for (var i = 0; i < doc.GetNumPages(); i++)
            {
                if (!doc_preflight.AddPage(i, null, null))
                {
                    throw new Exception(pdfix.GetError());
                }
            }

            // run document preflight
            if (!doc_preflight.Update(null, null))
            {
                throw new Exception(pdfix.GetError());
            }

            // save preflight to stream if needed
            var preflight_stm = pdfix.CreateMemStream();

            doc_preflight.SaveToStream(preflight_stm, PsDataFormat.kDataFormatJson, Pdfix.kSaveUncompressed);
            byte[] bytes = new byte[preflight_stm.GetSize()];
            preflight_stm.Read(0, bytes);
            System.Console.Write(System.Text.Encoding.UTF8.GetString(bytes));

            // output some document preflight values from the config
            for (var i = 0; i < doc.GetNumPages(); i++)
            {
                Console.WriteLine("Preflight results for page " + i.ToString());
                var page_preflight = doc_preflight.GetPageTemplate(i);
                if (page_preflight == null)
                {
                    throw new Exception(pdfix.GetError());
                }

                Console.WriteLine("logical rotate: " + page_preflight.GetLogicalRotate());
                Console.WriteLine("columns: " + page_preflight.GetNumColumns());
                var header_box = page_preflight.GetHeaderBBox();
                Console.WriteLine("header bbox: " + header_box.left + ", " + header_box.bottom +
                                  ", " + header_box.right + ", " + header_box.top);
                var footer_box = page_preflight.GetFooterBBox();
                Console.WriteLine("footer bbox: " + footer_box.left + ", " + footer_box.bottom +
                                  ", " + footer_box.right + ", " + footer_box.top);
                Console.WriteLine("");
            }

            doc.Close();
        }
        public static void Run(
            String openPath,                            // source PDF document
            String configPath,                          // configuration file
            PdfHtmlParams htmlParams                    // html conversion params
            )
        {
            Pdfix pdfix = PdfixEngine.Instance;

            PdfDoc doc = pdfix.OpenDoc(openPath, "");

            if (doc == null)
            {
                throw new Exception(pdfix.GetError());
            }

            var html_conv = doc.CreateHtmlConversion();

            if (html_conv == null)
            {
                throw new Exception(pdfix.GetError());
            }


            // customize conversion
            PsFileStream stm = pdfix.CreateFileStream(configPath, PsFileMode.kPsReadOnly);

            if (stm != null)
            {
                var doc_prelight = doc.GetTemplate();
                if (doc_prelight == null)
                {
                    throw new Exception(pdfix.GetError());
                }
                if (!doc_prelight.LoadFromStream(stm, PsDataFormat.kDataFormatJson))
                {
                    throw new Exception(pdfix.GetError());
                }
                stm.Destroy();
            }

            //htmlParams.type = PdfHtmlType.kPdfHtmlResponsive;
            htmlParams.flags |= Pdfix.kHtmlNoExternalCSS | Pdfix.kHtmlNoExternalJS |
                                Pdfix.kHtmlNoExternalIMG | Pdfix.kHtmlNoExternalFONT;
            //htmlParams.image_params.format = PdfImageFormat.kImageFormatJpg;
            //htmlParams.image_params.quality = 80;

            if (!html_conv.SetParams(htmlParams))
            {
                throw new Exception(pdfix.GetError());
            }

            var docStm = pdfix.CreateFileStream(Utils.GetAbsolutePath("output") + "/pages.html", PsFileMode.kPsTruncate);

            // prepare head
            docStm.Write(0, System.Text.Encoding.Default.GetBytes("<html>\n<head>\n<title>PDFix sample</title>\n</head>\n<body>\n"));
            docStm.Write(docStm.GetSize(), System.Text.Encoding.Default.GetBytes("<script>\n"));
            html_conv.SaveJavaScript(docStm);
            docStm.Write(docStm.GetSize(), System.Text.Encoding.Default.GetBytes("\n</script>\n<style>\n"));
            html_conv.SaveCSS(docStm);
            docStm.Write(docStm.GetSize(), System.Text.Encoding.Default.GetBytes("\n</style>\n"));

            // convert pages
            for (int i = 0; i < doc.GetNumPages(); i++)
            {
                if (!html_conv.AddPage(i, null, IntPtr.Zero))
                {
                    throw new Exception(pdfix.GetError());
                }
            }

            if (!html_conv.SaveToStream(docStm, null, IntPtr.Zero))
            {
                throw new Exception(pdfix.GetError());
            }

            docStm.Write(docStm.GetSize(), System.Text.Encoding.Default.GetBytes("</body>\n</html>"));

            html_conv.Destroy();
            docStm.Destroy();
            doc.Close();
        }
Beispiel #11
0
        public static void Run(
            String openPath,                            // source PDF document
            String savePath,                            // output PDF document
            String attachmentPath                       // attachment PDF
            )
        {
            Pdfix pdfix = PdfixEngine.Instance;

            PdfDoc doc = pdfix.OpenDoc(openPath, "");

            if (doc == null)
            {
                throw new Exception(pdfix.GetError());
            }

            // rect for the new annotation
            PdfRect annot_rect = new PdfRect()
            {
                left   = 300,
                right  = 328,
                bottom = 50,
                top    = 118
            };

            // create annotation dictionary and fill it
            PdsDictionary annot_dict  = doc.CreateDictObject(true);
            PdsArray      color_array = annot_dict.PutArray("C");

            color_array.PutNumber(0, 1);
            color_array.PutNumber(1, 0.33f);
            color_array.PutNumber(2, 0.25f);
            annot_dict.PutString("Contents", "AutoTag_Sample_original.pdf");
            annot_dict.PutNumber("F", 28);
            annot_dict.PutString("Name", "Paperclip");
            annot_dict.PutRect("Rect", annot_rect);
            annot_dict.PutString("Subj", "File Attachment");
            annot_dict.PutName("Subtype", "FileAttachment");
            annot_dict.PutString("T", "Mr PDFixer");
            annot_dict.PutName("Type", "Annot");

            PdsDictionary fs_dict = annot_dict.PutDict("FS");

            fs_dict.PutString("F", "AutoTag_Sample_original.pdf");
            fs_dict.PutName("Type", "Filespec");
            fs_dict.PutString("UF", "AutoTag_Sample_original.pdf");

            // open attachment doc
            var fileStm = pdfix.CreateFileStream(attachmentPath, PsFileMode.kPsReadOnly);

            if (fileStm == null)
            {
                throw new Exception(pdfix.GetError());
            }

            byte[] fileData = new byte[fileStm.GetSize()];
            fileStm.Read(0, fileData);

            // create stream object from attachment
            PdsStream filestream = doc.CreateStreamObject(true, null, fileData);

            PdsDictionary ef_dict = fs_dict.PutDict("EF");

            ef_dict.Put("F", filestream);

            // create annotation object from dictionary
            PdfAnnot annot = doc.GetAnnotFromObject(annot_dict);

            // add annotation on the first page
            var page = doc.AcquirePage(0);

            if (page == null)
            {
                throw new Exception(pdfix.GetError());
            }

            if (!page.AddAnnot(0, annot))
            {
                throw new Exception(pdfix.GetError());
            }

            page.Release();

            // save document
            if (!doc.Save(savePath, Pdfix.kSaveFull))
            {
                throw new Exception(pdfix.GetError());
            }

            doc.Close();
        }
Beispiel #12
0
        public static void Run(
            String email,                               // authorization email
            String licenseKey,                          // authorization license key
            String openPath,                            // source PDF document
            String savePath,                            // output folder for HTML content
            String configPath,                          // configuration file
            PdfHtmlParams htmlParams                    // html conversion params
            )
        {
            Pdfix pdfix = new Pdfix();

            if (pdfix == null)
            {
                throw new Exception("Pdfix initialization fail");
            }

            if (!pdfix.Authorize(email, licenseKey))
            {
                throw new Exception(pdfix.GetError());
            }

            PdfToHtml pdfToHtml = new PdfToHtml();

            if (pdfToHtml == null)
            {
                throw new Exception("PdfToHtml initialization fail");
            }

            if (!pdfToHtml.Initialize(pdfix))
            {
                throw new Exception(pdfix.GetError());
            }

            PdfDoc doc = pdfix.OpenDoc(openPath, "");

            if (doc == null)
            {
                throw new Exception(pdfix.GetError());
            }

            // customize conversion
            PsFileStream stm = pdfix.CreateFileStream(configPath, PsFileMode.kPsReadOnly);

            if (stm != null)
            {
                PdfDocTemplate docTmpl = doc.GetDocTemplate();
                if (docTmpl == null)
                {
                    throw new Exception(pdfix.GetError());
                }
                if (!docTmpl.LoadFromStream(stm, PsDataFormat.kDataFormatJson))
                {
                    throw new Exception(pdfix.GetError());
                }
                stm.Destroy();
            }

            // set html conversion params
            //htmlParams.type = PdfHtmlType.kPdfHtmlResponsive;
            //htmlParams.width = 1200;
            //htmlParams.flags |= PdfToHtml.kHtmlExportJavaScripts;
            //htmlParams.flags |= PdfToHtml.kHtmlExportFonts;
            //htmlParams.flags |= PdfToHtml.kHtmlRetainFontSize;
            //htmlParams.flags |= PdfToHtml.kHtmlRetainTextColor;
            htmlParams.flags |= PdfToHtml.kHtmlNoExternalCSS | PdfToHtml.kHtmlNoExternalJS |
                                PdfToHtml.kHtmlNoExternalIMG | PdfToHtml.kHtmlNoExternalFONT;

            PdfHtmlDoc htmlDoc = pdfToHtml.OpenHtmlDoc(doc);

            if (htmlDoc == null)
            {
                throw new Exception(pdfix.GetError());
            }

            // save common js and css for all pages
            PsStream docCss = pdfix.CreateFileStream(savePath + "/document.css",
                                                     PsFileMode.kPsTruncate);

            if (!pdfToHtml.SaveCSS(docCss))
            {
                throw new Exception(pdfix.GetError());
            }
            docCss.Destroy();

            PsStream docJs = pdfix.CreateFileStream(savePath + "/document.js",
                                                    PsFileMode.kPsTruncate);

            if (!pdfToHtml.SaveJavaScript(docJs))
            {
                throw new Exception(pdfix.GetError());
            }
            docJs.Destroy();

            PsStream docStm = pdfix.CreateFileStream(savePath + "/document.html",
                                                     PsFileMode.kPsTruncate);

            if (!htmlDoc.SaveDocHtml(docStm, htmlParams, null, IntPtr.Zero))
            {
                throw new Exception(pdfix.GetError());
            }
            docStm.Destroy();

            for (int i = 0; i < doc.GetNumPages(); i++)
            {
                string   pageFile = savePath + "/document_page" + i + ".html";
                PsStream pageStm  = pdfix.CreateFileStream(pageFile, PsFileMode.kPsTruncate);
                if (!htmlDoc.SavePageHtml(pageStm, htmlParams, i, null, IntPtr.Zero))
                {
                    throw new Exception(pdfix.GetError());
                }
                pageStm.Destroy();
            }

            htmlDoc.Close();
            doc.Close();
            pdfToHtml.Destroy();
            pdfix.Destroy();
        }
Beispiel #13
0
        public static void Run(
            String openPath,                            // source PDF document
            String savePath,                            // output PDF document
            String imgPath,                             // watermark to apply
            int start_page,                             // start page number
            int end_page,                               // end page number
            int order_top,                              // number specifying where in the page z-order the watermark should be added
            bool percentage_vals,                       // boolean specifying the units of horizValue and vertValue
            PdfAlignment h_align,                       // the horizontal alignment to be used when adding the watermark to a page
            PdfAlignment v_align,                       // the vertical alignment to be used when adding the watermark to a page
            float h_value,                              // the horizontal offset value to be used when adding the watermark on a page
            float v_value,                              // the vertical offset value to be used when adding the watermark on a page
            float scale,                                // the scale factor to be used when adding the watermark, with 1.0 meaning 100%
            float rotation,                             // the counter-clockwise rotation, in degrees, to be used when adding the watermark
            float opacity                               // the opacity to be used when adding the watermark
            )
        {
            Pdfix pdfix = PdfixEngine.Instance;

            PdfDoc doc = pdfix.OpenDoc(openPath, "");

            if (doc == null)
            {
                throw new Exception(pdfix.GetError());
            }

            var img_stm = pdfix.CreateFileStream(imgPath, PsFileMode.kPsReadOnly);

            if (img_stm == null)
            {
                throw new Exception(pdfix.GetError());
            }

            // identify image format from file path
            PdfImageFormat format = PdfImageFormat.kImageFormatJpg;

            if (Path.GetExtension(imgPath).ToLower() == ".png")
            {
                format = PdfImageFormat.kImageFormatPng;
            }

            var image_obj = doc.CreateXObjectFromImage(img_stm, format);

            if (image_obj == null)
            {
                throw new Exception(pdfix.GetError());
            }

            var page_num = doc.GetNumPages();

            if (end_page == -1 || end_page >= page_num)
            {
                end_page = page_num - 1;
            }

            if (start_page >= page_num || end_page < start_page)
            {
                throw new Exception("Page number out of range");
            }

            for (int i = start_page; i <= end_page; i++)
            {
                var page = doc.AcquirePage(i);
                if (page == null)
                {
                    throw new Exception(pdfix.GetError());
                }

                var content = page.GetContent();
                if (content == null)
                {
                    throw new Exception(pdfix.GetError());
                }

                var xobjdict = image_obj.GetStreamDict();
                var width    = xobjdict.GetNumber("Width");
                var height   = xobjdict.GetNumber("Height");

                // prepare the matrix
                var       page_mx     = page.GetDefaultMatrix();
                var       crop_rect   = page.GetCropBox();
                PdfMatrix page_mx_rev = Utils.PdfMatrixInverse(page_mx);

                // scale
                var width_scaled  = width * scale;
                var height_scaled = height * scale;

                var matrix = new PdfMatrix(width_scaled, 0, 0, height_scaled, 0, 0);

                if (rotation != 0.0f)
                {
                    matrix = Utils.PdfMatrixTranslate(matrix, -width_scaled / 2, -height_scaled / 2, false);
                    matrix = Utils.PdfMatrixRotate(matrix, (rotation / 180.0f) * Utils.kPi, false);
                    matrix = Utils.PdfMatrixTranslate(matrix, width_scaled / 2, height_scaled / 2, false);
                }

                // horizontal align
                var rect_h = crop_rect.right - crop_rect.left;
                var rect_v = crop_rect.top - crop_rect.bottom;
                if (h_align == PdfAlignment.kAlignmentCenter)
                {
                    matrix = Utils.PdfMatrixTranslate(matrix, (rect_h - width_scaled) / 2, 0.0f, false);
                }
                else if (h_align == PdfAlignment.kAlignmentRight)
                {
                    matrix = Utils.PdfMatrixTranslate(matrix, (rect_h - width_scaled), 0.0f, false);
                }

                // vertical align
                if (v_align == PdfAlignment.kAlignmentCenter)
                {
                    matrix = Utils.PdfMatrixTranslate(matrix, 0.0f, (rect_v - height_scaled) / 2, false);
                }
                else if (v_align == PdfAlignment.kAlignmentTop)
                {
                    matrix = Utils.PdfMatrixTranslate(matrix, 0.0f, (rect_v - height_scaled), false);
                }

                // horizontal and vertical offset
                var offs_h = percentage_vals ? rect_h * h_value : h_value;
                var offs_v = percentage_vals ? rect_v * v_value : v_value;

                //-offs_v because y coordinate from top to bottom
                matrix = Utils.PdfMatrixTranslate(matrix, offs_h, -offs_v, false);

                var position    = order_top == 1 ? -1 : 0;
                var imageobject = content.AddNewImage(position, image_obj, matrix);

                // set opacity of the image 0-255
                var graphicState = imageobject.GetGState();
                graphicState.color_state.fill_opacity = (int)(opacity * 255);
                imageobject.SetGState(graphicState);

                page.SetContent();

                page.Release();
            }

            if (!doc.Save(savePath, Pdfix.kSaveFull))
            {
                throw new Exception(pdfix.GetError());
            }

            doc.Close();
        }