public FileContentResult GetPdf()
        {
            var html = GetHtml();

            Byte[] bytes = new SimplePechkin(new GlobalConfig()).Convert(html);
            return(new FileContentResult(bytes, "application/pdf"));
        }
Beispiel #2
0
        public void GenerarPDFProyecto(string PK_ID_REPORTE, Reporte reporte, Detalle_Reporte detalle_Reporte, string nombre_cliente)
        {
            string pk_reporte = encryption.Decrypt(PK_ID_REPORTE);


            string tipo = "";

            tipo = "Reporte de Proyecto";



            byte[] pdfContent = new SimplePechkin(new GlobalConfig()).Convert("<html><body style='background - color: #E3F5FF '><CENTER> <TABLE style = 'font-family: arial;'  WIDTH ='80%'><TR><TD WIDTH ='75%'><h2 style = 'color: #1B252F'> Soluciones <strong> S.I.T.S.A </strong></h2><h4><a href = 'http://www.sitsacr.net'> www.sitsacr.net </a></h4><h4><a> [email protected] </a></h4><p> Tel: 2431 - 2925 </p><hr style = 'border-color: #707070;'><p> 50 m.Sur del Scotiabank Alajuela Centro <br/> <strong> 'Avenida Juan Lopez del corral' </strong></p><TD style = 'font-family: arial;'><center><h1 style = 'color: #1B252F'> S.I.T.S.A </h1> Soluciones Integrales en Tecnología </center><center> </TABLE><TABLE style = 'font-family: arial;'  WIDTH=80%><TR><TD ><hr style ='border-color: #707070;'><center><p style ='font-size: 24px;'> Reporte #" + pk_reporte + "</p> <h2>S.I.T.S.A</h2></center><TR> <TD><hr style = 'border-color: #707070;' ><label style = 'font-size: 18px;'><strong> Cliente:</strong> </label> " + nombre_cliente + " &nbsp &nbsp &nbsp <label style = 'font-size: 18px; font-family: arial;'> <strong> Fecha:</strong > </label > " + reporte.FECHA + "<br><br> <label style = 'font-size: 18px;'> <strong> Tipo de reporte: </strong > </label > &nbsp  " + tipo + "<br> <br>      <label style = 'font-size: 18px;' > <strong > Monto consumido: </strong> </label> &nbsp  " + detalle_Reporte.TARIFA + "<br><br></TABLE><CENTER><TABLE style = 'font-family: arial;'  WIDTH=80%><TR ><TR ><TD ><hr style= 'border-color: #707070;' ><label style= 'font-size: 18px;'><strong> Pendientes / Observaciones:</strong> </label><br><br><textarea style='width:100%; height: 100px; font-family: arial; font-size: 18px; font-color:black;'>" + reporte.OBSERVACION + "</textarea><br><br><CENTER><a href = 'https://localhost:44375/Reporte_Aceptacion.aspx?key=" + PK_ID_REPORTE + "'><button style='border-radius: 12px; font-family: arial; font-size: 16px; background-color: #e7e7e7; color: black;'>Cambiar estado</button></a></CENTER></TABLE></body</html>");



            // Folder where the file will be created
            string directory = "C:\\Pdf\\";
            // Name of the PDF
            string filename = "Reporte#" + pk_reporte + ".pdf";

            if (ByteArrayToFile(directory + filename, pdfContent))
            {
                Console.WriteLine("PDF Succesfully created");
            }
            else
            {
                Console.WriteLine("Cannot create PDF");
            }
        }
        /// <summary>
        /// Метод конвертирует html код в pdf файл
        /// Используется библиотека Pechkin
        /// </summary>
        /// <param name="pdfName">имя pdf файла</param>
        /// <param name="folderPath">путь к директории сохранения</param>
        private void HtmlToPdf(string pdfName, string folderPath = null)
        {
            GlobalConfig globalConfig = new GlobalConfig();

            globalConfig
            .SetMargins(EngineerMenu.PC.PrinterTopMarg, EngineerMenu.PC.PrinterRightMarg, EngineerMenu.PC.PrinterBottomMarg, EngineerMenu.PC.PrinterLeftMarg)
            .SetDocumentTitle("PdfDoc")
            .SetPaperSize(PaperKind.A4);

            IPechkin pechkin = new SimplePechkin(globalConfig);

            byte[] pdfBufferBytes = pechkin.Convert(_strBuilder.ToString());

            if (folderPath != null)
            {
                if (!Directory.Exists(folderPath))
                {
                    Directory.CreateDirectory(folderPath);
                }

                File.WriteAllBytes(folderPath + @"\" + pdfName, pdfBufferBytes);
            }
            else
            {
                File.WriteAllBytes(pdfName, pdfBufferBytes);
            }
        }
Beispiel #4
0
        public static void ConvertHTMLIntoPDF(string fileName)
        {
            Uri uri = new Uri(fileName);

            byte[] pdfBuf = new SimplePechkin(new GlobalConfig()).Convert(uri);
            File.WriteAllBytes(Tools.GetFilePathWithoutExtention(fileName) + ".pdf", pdfBuf);
        }
Beispiel #5
0
        private void OnFinished(SimplePechkin converter, bool success)
        {
            if (!success)
            {
                PdfExporter._logger.Error("PDF export failed to: " + this.OutputFilename);
                MessageBox.Show(LocalizationProvider.GetLocalizedString("PdfExportFailedMessage", true, "MarkdownPadStrings") + this.OutputFilename, LocalizationProvider.GetLocalizedString("PdfExportFailedTitle", false, "MarkdownPadStrings"), MessageBoxButton.OK, MessageBoxImage.Hand);
                return;
            }
            PdfExporter._logger.Trace("Exported PDF document to: " + this.OutputFilename);
            if (!this._settings.IO_OpenPdfFileAfterExport)
            {
                return;
            }
            BackgroundWorker backgroundWorker = new BackgroundWorker();

            backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(this.worker_RunWorkerCompleted);
            backgroundWorker.DoWork             += delegate(object param0, DoWorkEventArgs param1)
            {
                int num = 1;
                while (!System.IO.File.Exists(this.OutputFilename) && num <= 10)
                {
                    PdfExporter._logger.Trace(string.Concat(new object[]
                    {
                        "Try #",
                        num,
                        " ",
                        System.IO.File.Exists(this.OutputFilename)
                    }));
                    num++;
                    System.Threading.Thread.Sleep(300);
                }
            };
            backgroundWorker.RunWorkerAsync();
        }
Beispiel #6
0
        public void PechkinMultiConvert(string FilesDir)
        {
            //取得目標資料夾中所有符合條件的所有檔案
            string[] FilePath = Directory.GetFiles(FilesDir, "*");

            //開始逐檔將HTML轉PDF
            foreach (var i in FilePath)
            {
                Console.WriteLine("開始從" + i + "\n\r 產生:" + Path.GetFileNameWithoutExtension(i) + ".pdf");

                var          config  = new GlobalConfig();
                var          pechkin = new SimplePechkin(config);
                ObjectConfig oc      = new ObjectConfig();
                oc.SetPrintBackground(true).SetLoadImages(true);
                string HTML = ""; //讀入html
                try
                {                 // Open the text file using a stream reader.
                    using (StreamReader sr = new StreamReader(i))
                    {
                        // Read the stream to a string, and write the string to the console.
                        HTML = sr.ReadToEnd();
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("The file could not be read:");
                    Console.WriteLine(e.Message);
                }

                byte[] pdf = pechkin.Convert(oc, HTML);
                File.WriteAllBytes(FilesDir + @"\" + Path.GetFileNameWithoutExtension(i) + ".pdf", pdf);
                Console.WriteLine(Path.GetFileNameWithoutExtension(i) + ".pdf 轉換完成");
            }
        }
 public void GenerateMemberList(List <Member> members, DateTime snapshot)
 {
     try
     {
         string input = File.ReadAllText(Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName) + "\\Templates\\Html\\Template_Memberlist.htm");
         string str1  = "Ledenlijst: " + snapshot.ToShortDateString();
         this.FilePath = Path.GetTempPath() + ("tmp" + Util.Util.RandomString(10)) + ".pdf";
         StringBuilder stringBuilder = new StringBuilder();
         int           num           = 1;
         foreach (Member member in members)
         {
             stringBuilder.Append(num % 2 > 0 ? "<tr>" : "<tr class=\"alt\">");
             stringBuilder.Append("<td>" + (object)num + "</td>");
             stringBuilder.Append("<td>" + member.LastName + "</td>");
             stringBuilder.Append("<td>" + member.FirstName + "</td>");
             stringBuilder.Append("<td>" + member.ZipCode + "</td>");
             stringBuilder.Append("<td>" + member.City + "</td>");
             stringBuilder.Append("<td>" + member.Address + "</td>");
             stringBuilder.Append("<td>" + member.Country + "</td>");
             DateTime dateTime = member.BirthDate ?? new DateTime();
             stringBuilder.Append("<td>" + dateTime.ToShortDateString() + "</td>");
             stringBuilder.Append("<td>" + member.Email + "</td>");
             stringBuilder.Append("<td>" + member.TelephoneNr + "</td>");
             stringBuilder.Append("</tr>");
             ++num;
         }
         string str2 = new Regex("\\[(\\w+)\\]", RegexOptions.Compiled).Replace(input, (MatchEvaluator)(match => new Dictionary <string, string>((IEqualityComparer <string>)StringComparer.OrdinalIgnoreCase)
         {
             {
                 "Title",
                 str1
             },
             {
                 "ImagePath",
                 Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName) + "\\Templates\\Html"
             },
             {
                 "MemberOverviewTableElements",
                 stringBuilder.ToString()
             }
         }[match.Groups[1].Value]));
         GlobalConfig config = new GlobalConfig();
         config.SetMargins(new Margins(70, 45, 70, 45)).SetPaperSize(PaperKind.A4Rotated);
         SimplePechkin simplePechkin = new SimplePechkin(config);
         ObjectConfig  objectConfig  = new ObjectConfig();
         objectConfig.SetLoadImages(true);
         objectConfig.SetPrintBackground(true);
         objectConfig.SetZoomFactor(1.1);
         objectConfig.SetAllowLocalContent(true);
         ObjectConfig doc  = objectConfig;
         string       html = str2;
         File.WriteAllBytes(this.FilePath, simplePechkin.Convert(doc, html));
         PdfReportService.logger.Info("Memberlist PDF created: " + this.FilePath);
     }
     catch (Exception ex)
     {
         PdfReportService.logger.Error("Could not create temporary PDF file:" + ex.Message);
     }
 }
Beispiel #8
0
 protected void Button1_Click(object sender, EventArgs e)
 {
     if (Session["source"] != null)
     {
         byte[] pdfBuf = new SimplePechkin(new GlobalConfig()).Convert((string)Session["source"]);
         System.IO.File.WriteAllBytes("F:\\test.pdf", pdfBuf);
     }
 }
Beispiel #9
0
        private void B_Pdf_Click(object sender, EventArgs e)
        {
            GlobalConfig config = new GlobalConfig();

            config.SetOutputDpi(1600);
            config.SetOutputFormat(GlobalConfig.OutputFormat.Pdf);
            config.SetPaperSize(PaperKind.A4);



            SimplePechkin pechkin = new SimplePechkin(config);

            byte[] pdf = (pechkin).Convert(_main.HtmlPath);

            /*
             * byte[] pdf = new Pechkin.Synchronized.SynchronizedPechkin(
             * new Pechkin.GlobalConfig()).Convert(
             * new Pechkin.ObjectConfig()
             * .SetLoadImages(true)
             * .SetPrintBackground(true)
             * .SetScreenMediaType(true)
             * .SetCreateExternalLinks(true), _main.Html);
             */
            String pdfFile = _main.PdfPathToSave;

            if (File.Exists(pdfFile))
            {
                File.Delete(pdfFile);                //원래 있으면 지우고..
                System.Threading.Thread.Sleep(3000); //3초 기다림.
            }
            try
            {
                using (FileStream file = System.IO.File.Create(pdfFile))
                {
                    file.Write(pdf, 0, pdf.Length);
                    file.Close();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            if (C_OpenPdf.Checked)
            {
                String readerPath = (_main.PdfReaderPath.Length > 0)? _main.PdfReaderPath: FindAcrobatReader();

                if (readerPath.Length > 0)
                {
                    IOHandling.ProcessHandler.getProcessAfterStart(readerPath, "\"" + pdfFile + "\"");
                }
                else
                {
                    throw new Exception("Acrobat Reader가 깔려있지 않거나 external_exe_paths.txt에 PDF_READER항목을 비워두었습니다.");
                }
            }
        }
Beispiel #10
0
 private void OnScPhase(SimplePechkin converter, int phasenumber, string phasedescription)
 {
     if (InvokeRequired)
     {
         BeginInvoke((Action)(() => { Text = ("New Phase " + phasenumber + ": " + phasedescription); }));
     }
     else
     {
         Text = ("New Phase " + phasenumber + ": " + phasedescription);
     }
 }
Beispiel #11
0
 private void OnScFinished(SimplePechkin converter, bool success)
 {
     if (InvokeRequired)
     {
         BeginInvoke((Action)(() => { Text = ("Finished, Success: " + success); }));
     }
     else
     {
         Text = ("Finished, Success: " + success);
     }
 }
Beispiel #12
0
 private void OnScWarning(SimplePechkin converter, string warningtext)
 {
     if (InvokeRequired)
     {
         BeginInvoke((Action)(() => { MessageBox.Show("Warning: " + warningtext); }));
     }
     else
     {
         MessageBox.Show("Warning: " + warningtext);
     }
 }
Beispiel #13
0
 private static void Pechkin_Finished(SimplePechkin converter, bool success)
 {
     if (success)
     {
         Common.ShowStatusMessage("导出PDF成功");
     }
     else
     {
         Common.ShowStatusMessage("导出失败");
     }
 }
Beispiel #14
0
 private void OnScBegin(SimplePechkin converter, int expectedphasecount)
 {
     if (InvokeRequired)
     {
         BeginInvoke((Action)(() => { Text = ("Begin, PhaseCount: " + expectedphasecount); }));
     }
     else
     {
         Text = ("Begin, PhaseCount: " + expectedphasecount);
     }
 }
Beispiel #15
0
 private void OnScError(SimplePechkin converter, string errorText)
 {
     if (InvokeRequired)
     {
         BeginInvoke((Action)(() => { MessageBox.Show("Error: " + errorText); }));
     }
     else
     {
         MessageBox.Show("Error: " + errorText);
     }
 }
Beispiel #16
0
 private void OnScProgress(SimplePechkin converter, int progress, string progressdescription)
 {
     if (InvokeRequired)
     {
         // simple Invoke WILL NEVER SUCCEDE, because we're in the button click handler. Invoke will simply deadlock everything
         BeginInvoke((Action <string>)SetText, "Progress " + progress + ": " + progressdescription);
     }
     else
     {
         Text = ("Progress " + progress + ": " + progressdescription);
     }
 }
Beispiel #17
0
//html to Pdf
        public static void HtmlToPdf(string filePath, string html, bool isOrientation = false)
        {
            if (string.IsNullOrEmpty(html))
            {
                html = "Null";
            }
            // 创建全局信息
            GlobalConfig gc = new GlobalConfig();

            gc.SetMargins(new Margins(50, 50, 60, 60))
            .SetDocumentTitle("MarkWord")
            .SetPaperSize(PaperKind.A4)
            .SetPaperOrientation(isOrientation)
            .SetOutlineGeneration(true);


            //页面信息
            ObjectConfig oc = new ObjectConfig();

            oc.SetCreateExternalLinks(false)
            .SetFallbackEncoding(Encoding.UTF8)
            .SetLoadImages(true)
            .SetScreenMediaType(true)
            .SetPrintBackground(true);
            //.SetZoomFactor(1.5);

            var pechkin = new SimplePechkin(gc);

            pechkin.Finished        += Pechkin_Finished;
            pechkin.Error           += Pechkin_Error;
            pechkin.ProgressChanged += Pechkin_ProgressChanged;
            var buf = pechkin.Convert(oc, html);

            if (buf == null)
            {
                Common.ShowMessage("导出异常");
                return;
            }

            try
            {
                string     fn = filePath; //Path.GetTempFileName() + ".pdf";
                FileStream fs = new FileStream(fn, FileMode.Create);
                fs.Write(buf, 0, buf.Length);
                fs.Close();

                //Process myProcess = new Process();
                //myProcess.StartInfo.FileName = fn;
                //myProcess.Start();
            }
            catch { }
        }
Beispiel #18
0
        public void GenerarPDF(string PK_ID_REPORTE, Reporte reporte, List <Detalle_Reporte> detalles_reporte, String nombre_cliente)
        {
            string cadena = "", tipo = "";

            tipo = "Reporte de contrato";
            string pk_reporte = encryption.Decrypt(PK_ID_REPORTE);

            double horas_totales    = dao_reporte.ObtenerHorasTotales(reporte.ID_CONTRATO);
            double horas_consumidas = dao_reporte.ObtenerHorasConsumidas(reporte.ID_CONTRATO);


            double tarifa_total = 0;

            foreach (var dato in detalles_reporte)
            {
                string nombre_servicio = dao_reporte.ObtenerNombreServicio(dato.ID_SERVICIO);


                tarifa_total = tarifa_total + dato.TARIFA;

                cadena = cadena + "<tr><td>" + nombre_servicio + "</td>" +
                         "<td>" + dato.OBSERVACION + "</td>" +
                         "<td>" + dato.TARIFA + "</td>" +
                         "<td>" + dato.HORAS + "</td>";
            }



            byte[] pdfContent = new SimplePechkin(new GlobalConfig()).Convert("<html><body style='background - color: #E3F5FF '><CENTER> <TABLE style = 'font-family: arial;'  WIDTH ='80%'><TR><TD WIDTH ='75%'><h2 style = 'color: #1B252F'> Soluciones <strong> S.I.T.S.A </strong></h2><h4><a href = 'http://www.sitsacr.net'> www.sitsacr.net </a></h4><h4><a> [email protected] </a></h4><p> Tel: 2431 - 2925 </p><hr style = 'border-color: #707070;'><p> 50 m.Sur del Scotiabank Alajuela Centro <br/> <strong> 'Avenida Juan Lopez del corral' </strong></p><TD style = 'font-family: arial;'><center><h1 style = 'color: #1B252F'> S.I.T.S.A </h1> Soluciones Integrales en Tecnología </center><center> </TABLE><TABLE style = 'font-family: arial;'  WIDTH=80%><TR><TD ><hr style ='border-color: #707070;'><center><p style ='font-size: 24px;'> Reporte #" + pk_reporte + "</p> <h2>S.I.T.S.A</h2></center><TR> <TD><hr style = 'border-color: #707070;' ><label style = 'font-size: 18px;'><strong> Cliente:</strong> </label> " + nombre_cliente + " &nbsp &nbsp &nbsp <label style = 'font-size: 18px; font-family: arial;'> <strong> Fecha:</strong > </label > " + reporte.FECHA + "<br><br><br><br> <label style = 'font-size: 18px;'> <strong> Tipo de reporte: </strong > </label > &nbsp  " + tipo + "<br> <br><label style = 'font-size: 18px;'> <strong> Horas totales: </strong > </label > &nbsp " + horas_totales + " <br><br> <label style = 'font-size: 18px;'> <strong> Horas consumidas: </strong> </label > &nbsp " + reporte.CANTIDAD_HORAS + " <br><br> <label style = 'font-size: 18px;'> <strong > Horas disponibles: </strong ></label> &nbsp " + horas_consumidas + "</TABLE> <CENTER><TABLE style = 'font-family: arial;'  WIDTH=80%> <TR > <TR ><TD ><hr style = 'border-color: #707070;' ><label style = 'font-size: 18px;' ><strong > Servicios:</strong > </label > <br><br><table border style = 'width:100%;'> <thead ><tr ><th> Servicio </th ><th > Descripción </th ><th > Monto </th ><th > Horas </th ></tr></thead > <tbody >    " + cadena + "   </tbody>        </table><br><br>         <label style = 'font-size: 18px;' > <strong > Monto total: </strong> </label> &nbsp " + tarifa_total + "<br><br></TABLE><CENTER><TABLE style = 'font-family: arial;'  WIDTH=80%><TR ><TR ><TD ><hr style= 'border-color: #707070;' ><label style= 'font-size: 18px;'><strong> Pendientes / Observaciones:</strong> </label><br><br><textarea  style='width:100%; height: 100px; font-family: arial; font-size: 18px;'>" + reporte.OBSERVACION + "</textarea><br><br><CENTER><a href = 'https://localhost:44375/Reporte_Aceptacion.aspx?key=" + PK_ID_REPORTE + "'><button style='border-radius: 12px; font-family: arial; font-size: 16px; background-color: #e7e7e7; color: black;'>Cambiar estado</button></a></CENTER></TABLE></body</html>");



            // Folder where the file will be created
            string directory = "C:\\Pdf\\";
            // Name of the PDF
            string filename = "Reporte#" + pk_reporte + ".pdf";

            if (ByteArrayToFile(directory + filename, pdfContent))
            {
                Console.WriteLine("PDF Succesfully created");
            }
            else
            {
                Console.WriteLine("Cannot create PDF");
            }
        }
Beispiel #19
0
        /*
         * Asks for HTML Text, File Location, and File Name then creates a pdf containing the HTML text
         * at the given location with the given name.
         * Returns created file location.
         */
        private string CreatePDF(string pdfText, string fileLocation, string fileName)
        {
            // Creates file if none exists where the Daily Log exe is, if there is a file then it
            // does nothing
            System.IO.Directory.CreateDirectory(fileLocation);

            byte[] pdfBuffer = new SimplePechkin(new GlobalConfig()).Convert(pdfText);

            if (ByteArrayToFile(fileLocation + "\\" + fileName, pdfBuffer))
            {
                Console.WriteLine("PDF Succesfully created");
            }
            else
            {
                Console.WriteLine("Cannot create PDF");
            }

            // Returns where the pdf was created
            return(Path.GetFullPath(fileLocation + "\\" + fileName));
        }
Beispiel #20
0
        private void SaveHtmlAsPdf(string fName, string html)
        {
            GlobalConfig  cfg = new GlobalConfig();
            SimplePechkin sp  = new SimplePechkin(cfg);
            ObjectConfig  oc  = new ObjectConfig();

            oc.SetCreateExternalLinks(true)
            .SetFallbackEncoding(Encoding.ASCII)
            .SetLoadImages(true)
            .SetAllowLocalContent(true)
            .SetPrintBackground(true);

            byte[]     pdfBuf = sp.Convert(oc, "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"><title></title></head><body>" + html + "</body></html>");
            FileStream fs     = new FileStream(fName, FileMode.Create, FileAccess.ReadWrite);

            foreach (var byteSymbol in pdfBuf)
            {
                fs.WriteByte(byteSymbol);
            }
            fs.Close();
        }
Beispiel #21
0
        private static void WritePdfFromHtml(string html, string outputFile, string documentTitle, string cssFile, string headerHtmlFile, string footerHtmlFile)
        {
            GlobalConfig gc = new GlobalConfig();

            gc.SetPaperSize(System.Drawing.Printing.PaperKind.A4);
            gc.SetPaperOrientation(false);
            gc.SetDocumentTitle(documentTitle);

            SimplePechkin pechkin = new SimplePechkin(gc);
            ObjectConfig  oc      = new ObjectConfig();

            oc.SetAllowLocalContent(true);
            oc.SetPrintBackground(true);

            if (!string.IsNullOrEmpty(cssFile))
            {
                /// for some reason oc.SetUserStylesheetUri(new Uri(cssFile).AbsoluteUri) is not working, so although
                /// this looks hacky, it gets the job done
                html = @"<link href=""" + new Uri(cssFile).AbsoluteUri + @""" rel=""stylesheet"" type=""text/css"" />" + System.Environment.NewLine + html;
            }

            if (!string.IsNullOrEmpty(headerHtmlFile))
            {
                oc.Header.SetHtmlContent(new Uri(headerHtmlFile).AbsoluteUri);
            }

            if (!string.IsNullOrEmpty(footerHtmlFile))
            {
                oc.Footer.SetHtmlContent(new Uri(footerHtmlFile).AbsoluteUri);
            }

            try
            {
                System.IO.File.WriteAllBytes(outputFile, pechkin.Convert(oc, html));
            }
            catch (System.IO.IOException)
            {
                Console.WriteLine("The PDF file you are writing to is likely already open/in use");
            }
        }
Beispiel #22
0
        private void validateButton_Click(object sender, EventArgs e)
        {
            if (invoice.Customer == null)
            {
                Utils.Warning("ATTENTION !\n\nAucun Client n'a été choisi !");
                DialogResult = DialogResult.None;
                return;
            }

            invoice.Date            = this.date.Value;
            invoice.DiscountPercent = (float)this.reduct.Value;
            invoice.PaidAmount      = (float)this.rule.Value;
            invoice.Payment         = (Payment)this.PaymentMethods.SelectedItem;

            InvoiceManager.Instance.Save(invoice);
            if (invoice.Customer.Email != null)
            {
                byte[]     pdfBuf = new SimplePechkin(new GlobalConfig()).Convert(this.InvoiceHTML());
                Attachment att    = new Attachment(new MemoryStream(pdfBuf), "Invoice-" + invoice.Id.ToString() + "-" + DateTime.Now.ToShortDateString() + ".pdf");
                MailSender.Instance.sendInvoice(invoice.Customer, att);
            }
            DialogResult = DialogResult.OK;
        }
Beispiel #23
0
        static void Main(string[] args)
        {
            ReportMakerMain main = new ReportMakerMain();

            main.SetArgs(args);



            var dllDirectory = main.Functions._currentPath + "\\Webkit";

            Environment.SetEnvironmentVariable("PATH", Environment.GetEnvironmentVariable("PATH").Replace(";" + dllDirectory, "") + ";" + dllDirectory);

            //LoadAllDlls(Directory.GetCurrentDirectory()+"\\Webkit");

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            if (main.MakePdf)
            {
                bool         ret    = main.LoadReport();
                GlobalConfig config = new GlobalConfig();
                config.SetOutputDpi(1600);
                config.SetOutputFormat(GlobalConfig.OutputFormat.Pdf);
                config.SetPaperSize(PaperKind.A4);



                SimplePechkin pechkin = new SimplePechkin(config);

                byte[] pdf = (pechkin).Convert(main.HtmlPath);

                /*
                 * byte[] pdf = new Pechkin.Synchronized.SynchronizedPechkin(
                 * new Pechkin.GlobalConfig()).Convert(
                 * new Pechkin.ObjectConfig()
                 * .SetLoadImages(true)
                 * .SetPrintBackground(true)
                 * .SetScreenMediaType(true)
                 * .SetCreateExternalLinks(true), _main.Html);
                 */
                String pdfFile = main.PdfPathToSave;
                if (File.Exists(pdfFile))
                {
                    File.Delete(pdfFile);                //원래 있으면 지우고..
                    System.Threading.Thread.Sleep(3000); //3초 기다림.
                }
                try
                {
                    using (FileStream file = System.IO.File.Create(pdfFile))
                    {
                        file.Write(pdf, 0, pdf.Length);
                        file.Close();
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            else
            {
                ReportPreview helper = new ReportPreview(main);


                Application.Run(helper);
            }
        }
Beispiel #24
0
 private static void Pechkin_ProgressChanged(SimplePechkin converter, int progress, string progressDescription)
 {
     Common.ShowStatusMessage(progressDescription);
 }
Beispiel #25
0
        public static byte[] GenerarPDF(string html)
        {
            byte[] pdfBuffer = new SimplePechkin(new GlobalConfig()).Convert(new Pechkin.ObjectConfig().SetScreenMediaType(true), html);

            return(pdfBuffer);
        }
Beispiel #26
0
 private static void Pechkin_Error(SimplePechkin converter, string errorText)
 {
     Common.ShowStatusMessage("导出失败:" + errorText);
 }
Beispiel #27
0
        static void Main(string[] args)
        {
            Thread.CurrentThread.SetApartmentState(ApartmentState.STA);
            maxTreadNumber = int.Parse(ConfigurationManager.AppSettings["MaxThreadNumber"].ToString());
            string[] paras = args[0].Split(',');
            environment = paras[0];
            switch (environment)
            {
            case "1":
                environment = "DEV";
                break;

            case "2":
                environment = "QA";
                break;

            case "3":
                environment = "UAT";
                break;

            case "4":
                environment = "PROD";
                break;

            default:
                break;
            }

            // get data from databases
            string connetionStr = ConfigurationManager.ConnectionStrings["SQL" + environment].ConnectionString;

            string cmd = "SELECT [ID],[Control_ID],[Claim_Number],[Claimant_Number],[Form_ID],[sequence],[FormName] ,[URL],[URLDate],[URLFlag],[AttachmentName],[PDFName],[PDFDate] ,[Processed] FROM test where id> (1591748 +" + (1000 * int.Parse(paras[1])).ToString() + ") and id<=(1591748 +"
                         + (1000 * int.Parse(paras[1]) + 1000).ToString() + ")";// [TRANSFORMDB].[dbo].[CMT_ASPX_to_PDF_URL]";

            using (SqlConnection sc = new SqlConnection(connetionStr))
            {
                SqlCommand scmd = new SqlCommand(cmd, sc);
                try
                {
                    sc.Open();
                    SqlDataAdapter sda = new SqlDataAdapter(scmd);
                    DataSet        sd  = new DataSet();
                    sda.Fill(sd);
                    dataRowQueue = new ConcurrentQueue <DataRow>(sd.Tables[0].AsEnumerable().ToList <DataRow>());
                    sda.Dispose();
                }
                catch (Exception e)
                {
                    throw e;
                }
            }

            //get the html contents
            while (threadNumber < maxTreadNumber)
            {
                //control thread amount
                threadNumber++;
                var thread = getWebBrowerThread();
                //thread.SetApartmentState(ApartmentState.STA);
                thread.Start();
            }

            Console.WriteLine("started");

            while (dataRowQueue != null && dataRowQueue.Count > 0 && htmlQueue.Count == 0)
            {
                Thread.Sleep(1000);
            }

            while (pdfThreadNumber < maxTreadNumber)
            {
                pdfThreadNumber++;
                Thread pdfThread = new Thread(() =>
                {
                    GlobalConfig gc = new GlobalConfig();
                    gc.SetMargins(new Margins(100, 100, 100, 100));
                    gc.SetPaperSize(PaperKind.Letter);
                    IPechkin pechkin           = new SimplePechkin(gc);
                    ObjectConfig configuration = new ObjectConfig();
                    configuration.SetCreateExternalLinks(true).SetFallbackEncoding(Encoding.UTF8).SetLoadImages(true).SetCreateForms(false);
                    /*test error*/
                    int m = 0;
                    /*end*/

                    while (htmlQueue.Count != 0)
                    {
                        //while(threadNumber>=maxTreadNumber)
                        //    {
                        //        Thread.Sleep(1000);
                        //    }

                        /*test error*/
                        m++;
                        if (m == 50)
                        {
                            throw (new Exception("forced"));
                        }

                        /*end*/

                        while (dataRowQueue != null && dataRowQueue.Count > 0 && htmlQueue.Count == 0)
                        {
                            Thread.Sleep(1000);
                        }

                        /*isProcessDone = false;
                         * var subThread = new Thread(() =>
                         * {*/
                        //threadNumber++;

                        DataRow dr;
                        if (htmlQueue.TryDequeue(out dr))
                        {
                            rounds++;
                            try
                            {
                                byte[] pdfBuf = pechkin.Convert(configuration, dr["URL"].ToString());
                                var testFile  = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
                                                             "testpdf\\" + dr["Claim_Number"].ToString() + "_" + dr["Claimant_Number"].ToString() + "_" + dr["Form_ID"].ToString() + "_" + dr["sequence"].ToString() + ".pdf");
                                System.IO.File.WriteAllBytes(testFile, pdfBuf);
                                pdfBuf = null;
                                dr.Delete();
                                dr       = null;
                                testFile = null;
                            }
                            catch (Exception e)
                            {
                                MessageBox.Show(e.Message);
                            }
                            if (rounds % 1000 == 0)
                            {
                                GC.Collect();
                                GC.WaitForPendingFinalizers();
                            }
                        }

                        Application.ApplicationExit += Application_PDFApplicationExit;
                        Application.ExitThread();
                        Application.Exit();
                    }
                });
                pdfThread.Start();
            }
        }
Beispiel #28
0
        //private void ConvertToPdf()
        //{
        //    var loadPath = Server.MapPath("~/HtmlTemplates");
        //    var loadFile = Path.Combine(loadPath, "Test.html");
        //    var savePath = Server.MapPath("~/Pdf");
        //    var saveFile = Path.Combine(savePath, DateTime.Now.ToString("HH-mm-ss.fff") + ".pdf");

        //    var globalConfig = new GlobalConfig()
        //        .SetMargins(0, 0, 0, 0)
        //        .SetPaperSize(PaperKind.A4);

        //    var pdfWriter = new SynchronizedPechkin(globalConfig);

        //    pdfWriter.Error += OnError;
        //    pdfWriter.Warning += OnWarning;

        //    var objectConfig = new ObjectConfig()
        //        .SetPrintBackground(true)
        //        .SetIntelligentShrinking(false);

        //    var pdfBuffer = pdfWriter.Convert(objectConfig, File.ReadAllText(loadFile));

        //    File.WriteAllBytes(saveFile, pdfBuffer);
        //}

        private void OnWarning(SimplePechkin converter, string warningtext)
        {
            throw new NotImplementedException();
        }
Beispiel #29
0
 private void OnError(SimplePechkin converter, string errortext)
 {
     throw new NotImplementedException();
 }
Beispiel #30
0
 public byte[] GenerarPDFBytes(string content)
 {
     byte[] pdfContent = new SimplePechkin(new GlobalConfig()).Convert(content);
     return(pdfContent);
 }