Ejemplo n.º 1
0
        public static void CreatePdfFromHtml(string htmlFilePath)
        {
            var htmlFileInfo = new FileInfo(htmlFilePath);

            if (!htmlFileInfo.Exists)
            {
                throw new FileNotFoundException(htmlFileInfo.FullName);
            }

            Debug.Assert(htmlFileInfo.DirectoryName != null, "htmlFileInfo.DirectoryName != null");

            var tmpPdfFileInfo = new FileInfo(Path.Combine(htmlFileInfo.DirectoryName, "tmp.pdf"));
            var pdfOutFileInfo = new FileInfo(GetPdfEquivalentPath(htmlFileInfo.FullName));

            var gc = new GlobalConfig();

            gc.SetImageQuality(100);
            gc.SetOutputDpi(96);
            gc.SetPaperSize(1024, 1123);

            var oc = new ObjectConfig();

            oc.SetLoadImages(true);
            oc.SetAllowLocalContent(true);
            oc.SetPrintBackground(true);
            oc.SetZoomFactor(1.093);
            oc.SetPageUri(htmlFileInfo.FullName);

            if (tmpPdfFileInfo.Exists)
            {
                tmpPdfFileInfo.Delete();
            }

            IPechkin pechkin = new SynchronizedPechkin(gc);

            pechkin.Error += (converter, text) =>
            {
                Console.Out.WriteLine("error " + text);
            };

            pechkin.Warning += (converter, text) =>
            {
                Console.Out.WriteLine("warning " + text);
            };

            using (var file = File.OpenWrite(tmpPdfFileInfo.FullName))
            {
                var bytes = pechkin.Convert(oc);
                file.Write(bytes, 0, bytes.Length);
            }

            if (pdfOutFileInfo.Exists)
            {
                pdfOutFileInfo.Delete();
            }

            CreateDirectories(pdfOutFileInfo.DirectoryName);

            tmpPdfFileInfo.MoveTo(pdfOutFileInfo.FullName);
        }
        public FileStreamResult GeneraPDF(string Documento, string RIF, string Titulo, string URL)
        {
            // create global configuration object
            GlobalConfig gc = new GlobalConfig();

            // set it up using fluent notation
            gc.SetMargins(new Margins(50, 50, 0, 0))
            .SetDocumentTitle(Titulo)
            .SetPaperSize(PaperKind.Letter);
            //... etc

            // create converter
            IPechkin pechkin = new SynchronizedPechkin(gc);


            // create document configuration object
            ObjectConfig oc = new ObjectConfig();

            // and set it up using fluent notation too
            oc.SetCreateExternalLinks(false)
            .SetFallbackEncoding(Encoding.ASCII)
            .SetLoadImages(true)
            .SetPageUri(URL.Replace("GeneraPDF", ""));
            //... etc

            // convert document
            byte[] pdfBuf = pechkin.Convert(oc);

            HttpContext.Response.AddHeader("content-disposition", "attachment; filename=" + Titulo + "  " + Documento + ".pdf");
            MemoryStream ms = new MemoryStream(pdfBuf);

            return(new FileStreamResult(ms, "application/pdf"));
        }
Ejemplo n.º 3
0
        /// <summary>
        /// 导出PDF
        /// </summary>
        /// <param name="html">html页面字串</param>
        public void ExportPDF(string html)
        {
            SynchronizedPechkin sc = new SynchronizedPechkin(new GlobalConfig().SetMargins(new System.Drawing.Printing.Margins(100, 100, 100, 100)));

            byte[] buf = sc.Convert(new ObjectConfig(), html);

            var ms = new MemoryStream(buf);

            FileDownHelper.DownLoad(ms, "报价单.pdf");
            ms.Close();
        }
Ejemplo n.º 4
0
        public bool GeneratePDFFile()
        {
            GlobalConfig globalConfig = new GlobalConfig();

            globalConfig.SetMargins(new Margins(100, 100, 100, 100))
            .SetDocumentTitle("")
            .SetPaperSize(PaperKind.A4);

            IPechkin pechkin = new SynchronizedPechkin(globalConfig);

            ObjectConfig configuration = new ObjectConfig();

            configuration
            .SetAllowLocalContent(true)
            .SetPageUri(pathToHTML)
            .SetPrintBackground(true)
            .SetScreenMediaType(true);

            byte[] pdfContent = pechkin.Convert(configuration);

            SaveFileDialog saveFileDialog = new SaveFileDialog
            {
                Filter           = "PDF (*.pdf)|*.pdf",
                RestoreDirectory = true,
                Title            = "Choose a location to save your report",
                FileName         = "TaxInvoice" + metadata["FIRST_NAME"] + metadata["LAST_NAME"] + DateTime.Now.ToString("yyyyMMdd"),
                DefaultExt       = "pdf",
                CheckPathExists  = true,
                InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
            };

            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                if (SaveByteArrayToPDFFile(saveFileDialog.FileName, pdfContent))
                {
                    Process.Start(saveFileDialog.FileName);
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            else
            {
                return(false);
            }
        }
Ejemplo n.º 5
0
        public ActionResult ExportDemo()
        {
            SynchronizedPechkin sc = new SynchronizedPechkin(new GlobalConfig()
                                                             .SetMargins(new Margins()
            {
                Left = 0, Right = 0, Top = 0, Bottom = 0
            }));                                                                          //设置边距

            ObjectConfig oc = new ObjectConfig();

            oc.SetPrintBackground(true).SetRunJavascript(true).SetScreenMediaType(true)
            .SetLoadImages(true)
            .SetPageUri("http://drp.xiaoni.com/recommendcase/FindCaseDetail.aspx?findid=657");

            byte[] buf = sc.Convert(oc);

            return(File(buf, "application/pdf", "download.pdf"));
        }
Ejemplo n.º 6
0
        public void ExportPdf()
        {
            ObjectConfig doc          = new ObjectConfig().SetPrintBackground(this.IncludeCssBackground);
            GlobalConfig globalConfig = new GlobalConfig();

            globalConfig.SetDocumentTitle(this.DocumentTitle).SetOutlineGeneration(this.EnableOutlineGeneration).SetPaperOrientation(this._settings.IO_Pdf_LandscapeMode).SetMarginLeft(this._settings.IO_Pdf_MarginLeftInMillimeters).SetMarginTop(this._settings.IO_Pdf_MarginTopInMillimeters).SetMarginRight(this._settings.IO_Pdf_MarginRightInMillimeters).SetMarginBottom(this._settings.IO_Pdf_MarginBottomInMillimeters).SetPaperSize(this._settings.IO_Pdf_PaperSize);
            IPechkin pechkin = new SynchronizedPechkin(globalConfig);

            pechkin.Finished += new FinishEventHandler(this.OnFinished);
            try
            {
                byte[] bytes = pechkin.Convert(doc, this.HtmlContent);
                System.IO.File.WriteAllBytes(this.OutputFilename, bytes);
            }
            catch (System.Exception exception)
            {
                PdfExporter._logger.ErrorException("Error exporting PDF", exception);
                MessageBoxHelper.ShowErrorMessageBox(LocalizationProvider.GetLocalizedString("Error_PdfExportMessage", false, "MarkdownPadStrings"), LocalizationProvider.GetLocalizedString("Error_PdfExportTitle", false, "MarkdownPadStrings"), exception, "");
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// html生成PDF
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnhtml_Click(object sender, EventArgs e)
        {
            string        beforPath = txthtmlb.Text;
            string        afterPath = txthtmla.Text;
            List <string> htmlList  = new List <string>();
            DirectoryInfo folder    = new DirectoryInfo(beforPath);

            SynchronizedPechkin sc = new SynchronizedPechkin(new GlobalConfig()
                                                             .SetMargins(new Margins()
            {
                Left = 10, Right = 10, Top = 10, Bottom = 10
            })                                                                           //设置边距
                                                             .SetPaperOrientation(false) //设置纸张方向为横向
                                                             .SetPaperSize(210, 297)     //设置纸张大小210mm * 297mm
                                                             );
            string type = "*";

            try
            {
                foreach (FileInfo file in folder.GetFiles(type))
                {
                    StreamReader sr   = new StreamReader(file.FullName, Encoding.Default);
                    string       html = sr.ReadToEnd();
                    html = html.Replace("font-family", "font-familyss");
                    byte[]     buf       = sc.Convert(new ObjectConfig(), html);
                    string     afterName = afterPath + "\\" + file.Name.Split('.')[0] + ".pdf";
                    FileStream fs        = new FileStream(afterName, FileMode.Create);
                    fs.Write(buf, 0, buf.Length);
                    fs.Close();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("HTML生成PDF异常,请联系管理员!" + "\r\n" + ex.ToString());
            }
        }
Ejemplo n.º 8
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="htmlPath">for saving by pechkin,this parameter can be set with local path or url</param>
        /// <param name="pdfPath"></param>
        /// <returns></returns>
        public bool Save(string htmlPath, string pdfPath)
        {
            lock (this)
            {
                try
                {
                    config.SetPageUri(htmlPath);
                    Utility.LocalIOHelper.CheckDirectoryExist(pdfPath);
                    byte[] buf = null;
                    buf = pechkinTool.Convert(config);
                    if (buf == null)
                    {
                        return(false);
                    }

                    File.WriteAllBytes(pdfPath, buf);
                    return(true);
                }
                catch (Exception e)
                {
                    return(false);
                }
            }
        }
Ejemplo n.º 9
0
        private void OnConvertButtonClick(object sender, EventArgs e)
        {
            PerformanceCollector pc = new PerformanceCollector("PDF creation");

            //PechkinStatic.InitLib(false);

            pc.FinishAction("Library initialized");

            SynchronizedPechkin sc = new SynchronizedPechkin(new GlobalConfig().SetMargins(new Margins(300, 100, 150, 100))
                                                             .SetDocumentTitle("Ololo").SetCopyCount(1).SetImageQuality(50)
                                                             .SetLosslessCompression(true).SetMaxImageDpi(20).SetOutlineGeneration(true).SetOutputDpi(1200).SetPaperOrientation(true)
                                                             .SetPaperSize(PaperKind.Letter));

            pc.FinishAction("Converter created");

            sc.Begin           += OnScBegin;
            sc.Error           += OnScError;
            sc.Warning         += OnScWarning;
            sc.PhaseChanged    += OnScPhase;
            sc.ProgressChanged += OnScProgress;
            sc.Finished        += OnScFinished;

            pc.FinishAction("Event handlers installed");

            byte[] buf = sc.Convert(new ObjectConfig(), htmlText.Text);

            /*sc.Convert(new ObjectConfig().SetPrintBackground(true).SetProxyString("http://localhost:8888")
             * .SetAllowLocalContent(true).SetCreateExternalLinks(false).SetCreateForms(false).SetCreateInternalLinks(false)
             * .SetErrorHandlingType(ObjectConfig.ContentErrorHandlingType.Ignore).SetFallbackEncoding(Encoding.ASCII)
             * .SetIntelligentShrinking(false).SetJavascriptDebugMode(true).SetLoadImages(true).SetMinFontSize(16)
             * .SetRenderDelay(2000).SetRunJavascript(true).SetIncludeInOutline(true).SetZoomFactor(2.2), htmlText.Text);*/

            pc.FinishAction("conversion finished");

            if (buf == null)
            {
                MessageBox.Show("Error converting!");

                return;
            }

            //for (int i = 0; i < 1000; i++)
            {
                buf = sc.Convert(new ObjectConfig(), htmlText.Text);

                if (buf == null)
                {
                    MessageBox.Show("Error converting!");

                    return;
                }
            }

            pc.FinishAction("1 more conversions finished");

            try
            {
                string fn = Path.GetTempFileName() + ".pdf";

                FileStream fs = new FileStream(fn, FileMode.Create);
                fs.Write(buf, 0, buf.Length);
                fs.Close();

                pc.FinishAction("dumped file to disk");

                Process myProcess = new Process();
                myProcess.StartInfo.FileName = fn;
                myProcess.Start();

                pc.FinishAction("opened it");
            } catch { }

            pc.ShowInMessageBox(null);
        }
        // Method to Convert Template HTML with Dynamic Data to PDF and Save it on Server

        public ActionResult ConvertPdf()
        {
            // Setting Up Global Configuration for PDF writer

            GlobalConfig gc = new GlobalConfig();

            gc.SetMargins(new Margins(100, 100, 100, 100))
            .SetDocumentTitle("Test document")
            .SetPaperSize(PaperKind.Letter);


            // Initializing PECHKIN object with Global Configuration

            IPechkin pechkin = new SynchronizedPechkin(gc);

            // ANY model Object (Custom Model) with Data in It

            test newTest = new test {
                Id = 2, Name = "Arslan"
            };

            // Getting Image path from Server Folder. If any user/admin upload there image to Server
            // Path can vary according to your needs where you put your uploads.

            string imgPath = Server.MapPath("~/Content/") + "polar.jpg";

            // Method writting at Bottom to convert Image to Base 64. So you can print images on PDF
            // Just pass Image path string created above to it and it will return base64 string

            var base64Image = ImageToBase64(imgPath);

            // Reading TEMPLATE.HTML from stored location to be ready and converted into PDF
            // Converting HTML into String (Stream) to pass on network or replace tags inside its TEXT.

            string       body   = string.Empty;
            StreamReader reader = new StreamReader(Server.MapPath("~/Views/Shared/sample.html"));

            using (reader)
            {
                body = reader.ReadToEnd();
            }

            // REPLACING tags inside TEMPLATE.HTML with dynamic data Taken from any MODEL.

            body = body.Replace("{NAME}", newTest.Name);
            body = body.Replace("{ID}", Convert.ToString(newTest.Id));
            body = body.Replace("{SRC}", base64Image);                      // This is Image src <img src={SRC} > , replaced with BASE64 string

            // CONVERTING Body(html stream) to Bytes with PECHKIN to be Convert to PDF asnd able to store on server.

            byte[] pdfContent = pechkin.Convert(body);

            // Setting Up Directory Path. Where PDF files will be save on Server.

            string directory = Server.MapPath("~/SavedPDF/");

            // Setting up PDF File Name (Dynamic Name for every client Name with Date)

            string filename = "clientPDF_" + newTest.Name + "_" + DateTime.Now.ToString("dd-MMM-yyyy") + ".pdf";

            // Writing Byte Array (PDF CONTENT) to File completely.  If Success The SUCCESS messeg will be written on Console.

            if (ByteArrayToFile(directory + filename, pdfContent))
            {
                Console.WriteLine("PDF Succesfully created");
            }
            else
            {
                Console.WriteLine("Cannot create PDF");
            }

            // Returing to Main Page

            return(RedirectToAction("Index"));
        }
Ejemplo n.º 11
0
        public void Elabora(string XmlDaImpotare)
        {
            string xslFile = @"C:\TestEdicom\fatturaordinaria_v1.2.1.xsl";

            string xmlFile = XmlDaImpotare;

            string htmlFile = @"C:\TestEdicom\prova.HTML";

            string _NomePdf = NomePDF(XmlDaImpotare);

            listBox1.Items.Add(_NomePdf);

            XslCompiledTransform transform = new XslCompiledTransform();

            transform.Load(xslFile);

            transform.Transform(xmlFile, htmlFile);

            //MessageBox.Show("Ho ottenuto HTML");

            //EO.Pdf.HtmlToPdf.ConvertHtml( @"C:\TestEdicom\prova.HTML", @"C:\TestEdicom\prova.pdf");
            // create global configuration object
            GlobalConfig gc = new GlobalConfig();

            // set it up using fluent notation
            // Remember to import the following type:
            //     using System.Drawing.Printing;
            //
            // a new instance of Margins with 1-inch margins.
            gc.SetMargins(new Margins(100, 100, 100, 100))
            .SetDocumentTitle("Test document")
            .SetPaperSize(PaperKind.Letter);

            // Create converter
            IPechkin pechkin = new SynchronizedPechkin(gc);

            // Create document configuration object
            ObjectConfig configuration = new ObjectConfig();


            string HTML_FILEPATH = @"C:\TestEdicom\prova.HTML";

            // and set it up using fluent notation too
            configuration
            .SetAllowLocalContent(true)
            .SetPageUri(@"file:///" + HTML_FILEPATH);

            // Generate the PDF with the given configuration
            // The Convert method will return a Byte Array with the content of the PDF
            // You will need to use another method to save the PDF (mentioned on step #3)
            byte[] pdfContent = pechkin.Convert(configuration);

            // Folder where the file will be created
            string directory = @"C:\TestEdicom\" + _NomePdf;

            if (!Directory.Exists(directory))
            {
                Directory.CreateDirectory(directory);
            }
            // Name of the PDF
            string filename = _NomePdf + ".pdf";

            if (ByteArrayToFile(directory + "\\" + filename, pdfContent))
            {
                Console.WriteLine("PDF Succesfully created");
            }
            else
            {
                Console.WriteLine("Cannot create PDF");
            }

            //MessageBox.Show("Ho generato PDF");
            File.Move(XmlDaImpotare, Path.GetDirectoryName(XmlDaImpotare) + "\\Park\\" + Path.GetFileName(XmlDaImpotare));
            File.Copy(Path.GetDirectoryName(XmlDaImpotare) + "\\DATI PER REGISTRAZIONE.xlsx", directory + "\\DATI PER REGISTRAZIONE.xlsx");
        }
Ejemplo n.º 12
0
        public void Create()
        {
            Comprobante   oComprobante;
            string        pathXML     = @"E:\ASP NET\ApplicationXMLtoPDF\ApplicationXMLtoPDF\xml\archivoXML4.xml";
            XmlSerializer oSerializer = new XmlSerializer(typeof(Comprobante));

            using (StreamReader reader = new StreamReader(pathXML))
            {
                oComprobante = (Comprobante)oSerializer.Deserialize(reader);

                foreach (var oComplemento in oComprobante.Complemento)
                {
                    foreach (var oComplementoInterior in oComplemento.Any)
                    {
                        if (oComplementoInterior.Name.Contains("TimbreFiscalDigital"))
                        {
                            XmlSerializer oSerializerComplemento = new XmlSerializer(typeof(TimbreFiscalDigital));
                            using (var readerComplemento = new StringReader(oComplementoInterior.OuterXml))
                            {
                                oComprobante.TimbreFiscalDigital = (TimbreFiscalDigital)oSerializerComplemento.Deserialize(readerComplemento);
                            }
                        }
                    }
                }
            }

            //Paso 2 Aplicando Razor y haciendo HTML a PDF

            string path            = Server.MapPath("~") + "/";
            string pathHTMLTemp    = path + "miHTML.html";//temporal
            string pathHTPlantilla = path + "plantilla.html";
            string sHtml           = GetStringOfFile(pathHTPlantilla);
            string resultHtml      = "";

            resultHtml = Razor.Parse(sHtml, oComprobante);

            //Creamos el archivo temporal
            File.WriteAllText(pathHTMLTemp, resultHtml);



            GlobalConfig gc = new GlobalConfig();

            gc.SetMargins(new Margins(100, 100, 100, 100))
            .SetDocumentTitle("Test document")
            .SetPaperSize(PaperKind.Letter);

            // Create converter
            IPechkin pechkin = new SynchronizedPechkin(gc);

            // Create document configuration object
            ObjectConfig configuration = new ObjectConfig();


            string HTML_FILEPATH = pathHTMLTemp;

            // and set it up using fluent notation too
            configuration
            .SetAllowLocalContent(true)
            .SetPageUri(@"file:///" + HTML_FILEPATH);

            // Generate the PDF with the given configuration
            // The Convert method will return a Byte Array with the content of the PDF
            // You will need to use another method to save the PDF (mentioned on step #3)
            byte[] pdfContent = pechkin.Convert(configuration);
            ByteArrayToFile(path + "prueba.pdf", pdfContent);
            //eliminamos el archivo temporal
            File.Delete(pathHTMLTemp);
        }