/// <summary>
        /// ConvertUrlToPdf
        /// </summary>
        /// <param name="url"></param>
        /// <param name="articleid"></param>
        private static void ConvertUrlToPdf(string url, string articleid, bool WithWaterMark = false)
        {
            PdfDocument     doc     = new PdfDocument();
            PdfPageSettings setting = new PdfPageSettings();
            Thread          thread  = new Thread(() =>
            {
                doc.LoadFromHTML(url, false, true, true, setting);
            });

            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
            thread.Join();
            if (WithWaterMark)
            {
                foreach (PdfPageBase page in doc.Pages)
                {
                    PdfTilingBrush brush = new PdfTilingBrush(new SizeF(page.Canvas.ClientSize.Width / 2, page.Canvas.ClientSize.Height / 3));
                    brush.Graphics.SetTransparency(0.15f);
                    brush.Graphics.Save();
                    brush.Graphics.TranslateTransform(brush.Size.Width / 2, brush.Size.Height / 2);
                    brush.Graphics.RotateTransform(-45);
                    brush.Graphics.DrawString("www.codesnippet.info",
                                              new PdfFont(PdfFontFamily.Helvetica, 24), PdfBrushes.Violet, 0, 0,
                                              new PdfStringFormat(PdfTextAlignment.Center));
                    brush.Graphics.Restore();
                    brush.Graphics.SetTransparency(1);
                    page.Canvas.DrawRectangle(brush, new RectangleF(new PointF(0, 0), page.Canvas.ClientSize));
                }
            }
            //Save pdf file.
            doc.SaveToFile(PDFFolder + articleid + ".pdf");
            doc.Close();
        }
Пример #2
0
        String createPdfDocFromURL(string url, string outputName)
        {
            //Create a pdf document.
            PdfDocument doc = new PdfDocument();

            PdfPageSettings setting = new PdfPageSettings();

            setting.Size    = new SizeF(1000, 1000);
            setting.Margins = new Spire.Pdf.Graphics.PdfMargins(20);

            PdfHtmlLayoutFormat htmlLayoutFormat = new PdfHtmlLayoutFormat();

            htmlLayoutFormat.IsWaiting = true;

            Thread thread = new Thread(() =>
                                       { doc.LoadFromHTML(url, false, false, false, setting, htmlLayoutFormat); });

            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
            thread.Join();
            //Save pdf file.
            doc.SaveToFile($"{outputName}.pdf");
            doc.Close();
            return($"{outputName}.pdf");
        }
Пример #3
0
        public ActionResult HTMLPDF()
        {
            //Create a pdf document.
            PdfDocument doc = new PdfDocument();

            PdfPageSettings setting = new PdfPageSettings();

            setting.Size    = new SizeF(1000, 1000);
            setting.Margins = new Spire.Pdf.Graphics.PdfMargins(20);

            PdfHtmlLayoutFormat htmlLayoutFormat = new PdfHtmlLayoutFormat();

            htmlLayoutFormat.IsWaiting = true;

            doc.
            String url = "https://www.wikipedia.org/";

            Thread thread = new Thread(() =>
                                       { doc.LoadFromHTML(url, false, false, false, setting, htmlLayoutFormat); });

            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
            thread.Join();
            //Save pdf file.
            doc.SaveToFile(@"C:\PDFTest\output-wiki.pdf");
            doc.Close();
            //Launching the Pdf file.
            //System.Diagnostics.Process.Start("output-wiki.pdf");

            return(View());
        }
Пример #4
0
        public string Generate()
        {
            int      index   = 1;
            XElement element = new XElement("root",
                                            new XElement("start_day", InvoiceData.StartDate.ToString("dd", CultureInfo.InvariantCulture)),
                                            new XElement("start_month", Utils.Utils.GetMonthText(InvoiceData.StartDate.Month)),
                                            new XElement("start_year", InvoiceData.StartDate.ToString("yyyy", CultureInfo.InvariantCulture) + "წ"),
                                            new XElement("end_day", InvoiceData.EndDate.ToString("dd", CultureInfo.InvariantCulture)),
                                            new XElement("end_month", Utils.Utils.GetMonthText(InvoiceData.EndDate.Month)),
                                            new XElement("end_year", InvoiceData.EndDate.ToString("yyyy", CultureInfo.InvariantCulture) + "წ"),
                                            new XElement("num", InvoiceData.Num),
                                            new XElement("abonent_code", InvoiceData.AbonentCode),
                                            new XElement("abonent_name", InvoiceData.AbonentName),
                                            new XElement("abonent_address", InvoiceData.AbonentAddress),
                                            new XElement("abonent_telephone", InvoiceData.AbonentPhone),
                                            new XElement("summ", InvoiceData.Items.Sum(i => i.Amount)),
                                            new XElement("amount_letter", NumberToString.GetNumberGeorgianString((decimal)InvoiceData.Items.Sum(i => i.Amount))),
                                            new XElement("items", InvoiceData.Items.Select(it => new XElement("item",
                                                                                                              new XElement("loop", index++),
                                                                                                              new XElement("product", it.Name),
                                                                                                              new XElement("amount", it.Amount)))));

            string file_name = GetTempFilePathWithExtension("Invoice_" + InvoiceData.AbonentCode + "_" + InvoiceData.StartDate.ToString("ddMMyyyyHHmmss"));

            try
            {
                XslCompiledTransform _transform = new XslCompiledTransform(false);
                _transform.Load(Path.Combine(HostingEnvironment.ApplicationPhysicalPath, "App_Data", "Invoice.xslt"));

                using (StringWriter sw = new StringWriter())
                {
                    _transform.Transform(new XDocument(element).CreateNavigator(), new XsltArgumentList(), sw);

                    using (PdfDocument pdf = new PdfDocument())
                    {
                        PdfHtmlLayoutFormat htmlLayoutFormat = new PdfHtmlLayoutFormat()
                        {
                            IsWaiting = false
                        };
                        PdfPageSettings setting = new PdfPageSettings()
                        {
                            Size = PdfPageSize.A4
                        };

                        Thread thread = new Thread(() => { pdf.LoadFromHTML(sw.ToString(), false, setting, htmlLayoutFormat); });
                        thread.SetApartmentState(ApartmentState.STA);
                        thread.Start();
                        thread.Join();

                        pdf.SaveToFile(file_name, FileFormat.PDF);
                    }
                }
            }
            catch
            {
                file_name = string.Empty;
            }

            return(file_name);
        }
Пример #5
0
        public static byte[] SpirePDFHtmlToPDF(string html)
        {
            byte[] ret = null;

            //using (MemoryStream ms = new MemoryStream())
            //{
            //    Spire.Pdf.HtmlConverter.Qt.HtmlConverter.Convert(
            //    html,
            //    //memory stream
            //    ms,
            //    //enable javascript
            //    true,
            //    //load timeout
            //    10 * 1000,
            //    //page size
            //    new SizeF(612, 792),
            //    //page margins
            //    new Spire.Pdf.Graphics.PdfMargins(0),
            //    //load from content type
            //    LoadHtmlType.SourceCode
            //    );
            //}

            using (MemoryStream ms = new MemoryStream())
            {
                //Create a pdf document.
                Spire.Pdf.PdfDocument doc = new Spire.Pdf.PdfDocument();

                PdfPageSettings setting = new PdfPageSettings();

                //setting.Size = new SizeF(1000, 1000);
                setting.Size        = Spire.Pdf.PdfPageSize.A4;
                setting.Orientation = Spire.Pdf.PdfPageOrientation.Portrait;
                setting.Margins     = new Spire.Pdf.Graphics.PdfMargins(20);

                doc.Template.Top = GetHeader(doc, setting.Margins);
                //apply blank templates to other parts of page template
                doc.Template.Bottom = new PdfPageTemplateElement(doc.PageSettings.Size.Width, setting.Margins.Bottom);
                doc.Template.Left   = new PdfPageTemplateElement(setting.Margins.Left, doc.PageSettings.Size.Height);
                doc.Template.Right  = new PdfPageTemplateElement(setting.Margins.Right, doc.PageSettings.Size.Height);

                PdfHtmlLayoutFormat htmlLayoutFormat = new PdfHtmlLayoutFormat();
                htmlLayoutFormat.IsWaiting = true;

                Thread thread = new Thread(() =>
                                           { doc.LoadFromHTML(html, true, setting, htmlLayoutFormat); });
                thread.SetApartmentState(ApartmentState.STA);
                thread.Start();
                thread.Join();

                //Save pdf file.
                doc.SaveToStream(ms);
                doc.Close();

                ret = ms.ToArray();
            }

            return(ret);
        }
Пример #6
0
        public PdfDocument CrearDocPDF(string rutaFichero, /*Usuario user,*/ Dictionary<string, List<Libro>> coleccionLibrosCarrito, string infoCookieLibros)
        {
            PdfDocument miFactura = new PdfDocument();

            PdfHtmlLayoutFormat htmlLayoutFormat = new PdfHtmlLayoutFormat();

            htmlLayoutFormat.IsWaiting = false;

            PdfPageSettings setting = new PdfPageSettings();
            setting.Size = PdfPageSize.A4;

            //String facturaHTML = File.ReadAllText(rutaFichero + "PlantillaFactura.html");
            String facturaHTML = GenerarFacturaEnHTML(rutaFichero + "Imagenes/", coleccionLibrosCarrito.Values.ElementAt(0), /*user,*/ infoCookieLibros);

            List<string> nombreKey = coleccionLibrosCarrito.Keys.ToList();
            string keyString = "";
            foreach (string key in nombreKey)
            {
                keyString = key;
                keyString = keyString.Replace('/', '_').Replace(' ', '_').Replace(':', '_');
            }

            Thread thread = new Thread(() =>
            {
                miFactura.LoadFromHTML(facturaHTML, false, setting, htmlLayoutFormat);
                //miFactura.LoadFromHTML(facturaHTML, false, true, true);
            });

            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
            thread.Join();

            //string filePath = rutaFichero + "facturas/" + user.loginUsuario + keyString + ".pdf";

            //if (!File.Exists(filePath))
            //{
            //    FileStream f = File.Create(filePath);
            //    f.Close();
            //}
            try
            {
                //  miFactura.SaveToFile(rutaFichero + "Facturas/" + /*user.alias + keyString +*/ "Recibo.pdf");
                miFactura.SaveToFile("Recibo.pdf");
                mandar_email(miFactura);
            }
            catch (Exception e)
            {

            }


            //System.Diagnostics.Process.Start(rutaFichero + "facturas/" + user.loginUsuario + keyString + ".pdf");

            return miFactura;
        }
Пример #7
0
        //public PdfDocument CrearDocPDF(string rutaFichero, Usuario user, Dictionary<string, List<Libro>> coleccionLibrosCarrito)
        //{
        //    String facturaHTML = GenerarFacturaEnHTML(rutaFichero + "imagenes/", coleccionLibrosCarrito.Values.ElementAt(0));

        //    //PdfDocument miFactura = new PdfDocument();

        //    System.Threading.Thread thread = new System.Threading.Thread(() =>
        //    {
        //        PdfDocument fact = new PdfDocument();

        //        fact.LoadFromHTML(facturaHTML, true, true, false);
        //        fact.SaveToFile("C:/Users/karol/Desktop/facturas/" + user.loginUsuario + "_" + coleccionLibrosCarrito.Keys.ToString() + ".pdf");
        //    });
        //    thread.SetApartmentState(System.Threading.ApartmentState.STA);
        //    thread.Start();
        //    return null;
        //    /*
        //    Task<PdfDocument> generadorPDF = Task.Factory.StartNew<PdfDocument>((stringHTML) =>
        //    {
        //        string factHTML = (string)stringHTML;
        //        PdfDocument fact = new PdfDocument();
        //        fact.LoadFromHTML(factHTML,true,true,false);
        //        return fact;

        //    }, facturaHTML,
        //       System.Threading.CancellationToken.None,
        //       TaskCreationOptions.None ,
        //       TaskScheduler.FromCurrentSynchronizationContext());

        //    //generadorPDF.Start();
        //    generadorPDF.Wait(); //...nos aseguramos que el hilo acabe

        //    generadorPDF.Result.SaveToFile("C:/Users/karol/Desktop/facturas/" + user.loginUsuario + "_" + coleccionLibrosCarrito.Keys.ToString() + ".pdf"); //("CAROLINA_13/11/2015_15:10:25.pdf")

        //    //si en el pdf lo quiero grabar en un fichero en el servidor llamaria a miFactura.SaveToFile("nombre_fichero.pdf")

        //    return generadorPDF.Result;
        //    */

        //}

        public PdfDocument CrearDocPDF(string rutaFichero, Usuario user, Dictionary <string, List <Libro> > coleccionLibrosCarrito, string infoCookieLibros)
        {
            PdfDocument miFactura = new PdfDocument();

            PdfHtmlLayoutFormat htmlLayoutFormat = new PdfHtmlLayoutFormat();

            htmlLayoutFormat.IsWaiting = false;

            PdfPageSettings setting = new PdfPageSettings();

            setting.Size = PdfPageSize.A4;

            //String facturaHTML = File.ReadAllText(rutaFichero + "PlantillaFactura.html");
            String facturaHTML = GenerarFacturaEnHTML(rutaFichero + "imagenes/", coleccionLibrosCarrito.Values.ElementAt(0), user, infoCookieLibros);

            List <string> nombreKey = coleccionLibrosCarrito.Keys.ToList();
            string        keyString = "";

            foreach (string key in nombreKey)
            {
                keyString = key;
                keyString = keyString.Replace('/', '_').Replace(' ', '_').Replace(':', '_');
            }

            Thread thread = new Thread(() =>
            {
                miFactura.LoadFromHTML(facturaHTML, false, setting, htmlLayoutFormat);
                //miFactura.LoadFromHTML(facturaHTML, false, true, true);
            });

            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
            thread.Join();

            //string filePath = rutaFichero + "facturas/" + user.loginUsuario + keyString + ".pdf";

            //if (!File.Exists(filePath))
            //{
            //    FileStream f = File.Create(filePath);
            //    f.Close();
            //}
            try
            {
                miFactura.SaveToFile(rutaFichero + "facturas/" + user.loginUsuario + keyString + ".pdf");
            }
            catch (Exception e)
            {
            }


            //System.Diagnostics.Process.Start(rutaFichero + "facturas/" + user.loginUsuario + keyString + ".pdf");

            return(miFactura);
        }
Пример #8
0
        private void BeginRowLayout(object sender, BeginRowLayoutEventArgs args)
        {
            PdfCellStyle cellstyle = new PdfCellStyle();

            cellstyle.StringFormat = new PdfStringFormat(PdfTextAlignment.Center);
            cellstyle.Font         = new PdfTrueTypeFont(new Font("Arial", 8f), true);
            args.CellStyle         = cellstyle;

            PdfPageSettings ps = new PdfPageSettings();

            ps.Orientation = PdfPageOrientation.Landscape;
        }
Пример #9
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="html"></param>
        public static void ConvertHtmlToPdf(string html)
        {
            //Create a pdf document.
            PdfDocument         doc    = new PdfDocument();
            PdfPageSettings     page   = new PdfPageSettings();
            PdfHtmlLayoutFormat format = new PdfHtmlLayoutFormat();

            doc.LoadFromHTML(html, true, page, format);
            //Save pdf file.
            doc.SaveToFile("sample.pdf");
            doc.Close();
            //Launching the Pdf file.
            System.Diagnostics.Process.Start("sample.pdf");
        }
Пример #10
0
        protected void Schedule1_OnServerExportPDF(object sender, ScheduleEventArgs e)
        {
            ScheduleProperties scheduleObject = new SchedulePDFExport().ScheduleSerializeModel(e.Arguments["model"].ToString());

            scheduleObject.BlockoutSettings.DataSource = (IEnumerable) new JavaScriptSerializer().Deserialize(e.Arguments["blockedApp"].ToString(), typeof(IEnumerable));
            IEnumerable     scheduleAppointments = (IEnumerable) new JavaScriptSerializer().Deserialize(e.Arguments["processedApp"].ToString(), typeof(IEnumerable));
            PdfPageSettings pageSettings         = new PdfPageSettings(50f)
            {
                Orientation = PdfPageOrientation.Landscape
            };
            PdfDocument document = new PdfExport().Export(scheduleObject, scheduleAppointments, ExportTheme.FlatLime, Request.Form["locale"], pageSettings);

            document.Save("Schedule.pdf", Response, HttpReadType.Save);
        }
Пример #11
0
        public static bool GeneratePdf(List <EmailModel> messages, string filePath, out string errorMessage)
        {
            errorMessage = null;
            try
            {
                PdfDocument         pdf = new PdfDocument();
                PdfHtmlLayoutFormat htmlLayoutFormat = new PdfHtmlLayoutFormat();
                htmlLayoutFormat.IsWaiting = false;
                htmlLayoutFormat.FitToPage = Clip.Width;
                PdfPageSettings setting = new PdfPageSettings();
                setting.Size = PdfPageSize.A4;
                setting.SetMargins(3, 2);
                string htmlCode                    = File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "HtmlTemplate.html"));
                int    repeatAreaStartIndex        = htmlCode.IndexOf("@REPEATAREA@");
                int    repeatAreaEndIndex          = htmlCode.LastIndexOf("@REPEATAREA@") + "@REPEATAREA@".Length;
                int    repeatAreaContentStartIndex = htmlCode.IndexOf("@REPEATAREA@") + "@REPEATAREA@".Length;
                string repeatArea                  =
                    htmlCode.Substring(
                        repeatAreaContentStartIndex,
                        htmlCode.LastIndexOf("@REPEATAREA@") - repeatAreaContentStartIndex).Trim();
                string messageHtml = "";
                foreach (var message in messages)
                {
                    messageHtml +=
                        repeatArea.Replace("@FROM@", message.From)
                        .Replace("@SUBJECT@", message.Subject)
                        .Replace("@BODY@", message.Body)
                        .Replace("@RECEIVEDON@", message.ReceivedOn);
                }
                htmlCode = htmlCode.Remove(repeatAreaStartIndex, repeatAreaEndIndex - repeatAreaStartIndex);
                htmlCode = htmlCode.Insert(repeatAreaStartIndex, messageHtml);
                Thread thread = new Thread(() =>
                {
                    pdf.LoadFromHTML(htmlCode, false, setting, htmlLayoutFormat);
                });
                thread.SetApartmentState(ApartmentState.STA);
                thread.Start();
                thread.Join();
                pdf.SaveToFile(filePath);
                System.Diagnostics.Process.Start(filePath);
                return(true);
            }
            catch (Exception exp)
            {
                errorMessage = exp.Message;
            }

            return(false);
        }
        public ActionResult ExportAsPDF(string scheduleModel)
        {
            ScheduleProperties scheduleObject = new SchedulePDFExport().ScheduleSerializeModel(Request.Form["ScheduleModel"]);

            scheduleObject.BlockoutSettings.DataSource = (IEnumerable) new JavaScriptSerializer().Deserialize(Request.Form["ScheduleProcesedIntervalsApps"], typeof(IEnumerable));
            IEnumerable     scheduleAppointments = (IEnumerable) new JavaScriptSerializer().Deserialize(Request.Form["ScheduleProcesedApps"], typeof(IEnumerable));
            PdfPageSettings pageSettings         = new PdfPageSettings(50f)
            {
                Orientation = PdfPageOrientation.Landscape
            };
            PdfDocument document = new PdfExport().Export(scheduleObject, scheduleAppointments, ExportTheme.FlatSaffron, Request.Form["locale"], pageSettings);

            document.Save("Schedule.pdf", HttpContext.ApplicationInstance.Response, HttpReadType.Save);
            return(RedirectToAction("PDFExportController"));
        }
Пример #13
0
        public ActionResult DownloadPostPdf(int?id)
        {
            try
            {
                var rr = Session["OrgId"].ToString();
                int i  = Convert.ToInt32(rr);

                //Get Post
                var postbody = db.Posts.Where(x => x.PostId == id)
                               .Where(x => x.OrgId == i)
                               .Select(x => x.PostContent)
                               .FirstOrDefault();

                //Get Post Subject
                var postsubject = db.Posts.Where(x => x.PostId == id)
                                  .Where(x => x.OrgId == i)
                                  .Select(x => x.PostSubject)
                                  .FirstOrDefault();

                PdfDocument         pdf = new PdfDocument();
                PdfHtmlLayoutFormat htmlLayoutFormat = new PdfHtmlLayoutFormat();
                htmlLayoutFormat.IsWaiting = false;
                PdfPageSettings setting = new PdfPageSettings();
                setting.Size = PdfPageSize.A4;
                string htmlCode = postbody;
                Thread thread   = new Thread(() => { pdf.LoadFromHTML(htmlCode, false, setting, htmlLayoutFormat); });
                thread.SetApartmentState(ApartmentState.STA);
                thread.Start();
                thread.Join();

                var filePath = Server.MapPath("~/Files/UploadedFiles/");
                var fileName = postsubject + ".pdf";

                filePath = filePath + Path.GetFileName(fileName);
                pdf.SaveToFile(filePath);
                return(File(filePath, "application/pdf", postsubject + ".pdf"));
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return(Redirect("~/ErrorHandler.html"));
            }
        }
Пример #14
0
        /// <summary>将 Html 文本保存为 Pdf 文件</summary>
        /// <param name="html">html 文本</param>
        /// <param name="savePath">pdf 文件完整路径</param>
        public static void SavePdfFromHtml(string html, string savePath)
        {
            // html -> pdf
            var doc     = new PdfDocument();
            var setting = new PdfPageSettings();

            setting.Size    = new SizeF(1000, 1000);
            setting.Margins = new Spire.Pdf.Graphics.PdfMargins(20);
            var format = new PdfHtmlLayoutFormat();

            format.IsWaiting = true;

            //doc.LoadFromHTML(html, true, setting, format);  // 直接写会报错,参考 https://blog.csdn.net/m0_37693130/article/details/86687509
            var thread = new Thread(() => { doc.LoadFromHTML(html, true, setting, format); });

            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
            thread.Join();

            doc.SaveToFile(savePath);
            doc.Close();
        }
        public void CreatePDFFactor()
        {
            LoadFactorData();
            PdfDocument         pdf = new PdfDocument();
            PdfHtmlLayoutFormat htmlLayoutFormat = new PdfHtmlLayoutFormat();

            //webBrowser load html whether Waiting
            htmlLayoutFormat.IsWaiting = false;
            //page setting
            PdfPageSettings setting = new PdfPageSettings();

            setting.Size = PdfPageSize.A4;

            //Get innerHtml of Panel Control
            var sb_htmlCode = new StringBuilder();

            Panel1.RenderControl(new HtmlTextWriter(new StringWriter(sb_htmlCode)));
            string htmlCode = sb_htmlCode.ToString();

            //use single thread to generate the pdf from above html code
            Thread thread = new Thread(() =>
                                       { pdf.LoadFromHTML(htmlCode, false, setting, htmlLayoutFormat); });

            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
            thread.Join();

            // Save the file to PDF and preview it.
            string path = Server.MapPath("~/output.pdf");

            pdf.SaveToFile(path);
            CopyAndRenameFile();

            // System.Diagnostics.Process.Start(path);
            SendMail();
            Panel1.Visible = false;
        }
Пример #16
0
        private void button1_Click(object sender, EventArgs e)
        {
            //Create a pdf document.
            PdfDocument     doc  = new PdfDocument();
            PdfPageSettings pgSt = new PdfPageSettings();

            pgSt.Size = PdfPageSize.A4;

            PdfHtmlLayoutFormat htmlLayoutFormat = new PdfHtmlLayoutFormat();

            htmlLayoutFormat.IsWaiting = false;

            String htmlpath = @"..\..\..\..\..\..\Data\FromHTML.htm";
            string source   = File.ReadAllText(htmlpath);

            doc.LoadFromHTML(source, true, pgSt, htmlLayoutFormat);

            //Save pdf file.
            doc.SaveToFile("FromHTML.pdf");
            doc.Close();

            //Launch the file.
            PDFDocumentViewer("FromHTML.pdf");
        }
Пример #17
0
        protected void Grid1_ServerPdfExporting(object sender, GridEventArgs e)
        {
            PdfExport exp = new PdfExport();

            SummaryGridBind();
            if (dsSummary.Tables[0].Rows.Count > 0)
            {
                DataTable dtSummary = dsSummary.Tables[0];
                //List<DataRow> list = FamilyDetails.AsEnumerable().ToList();
                List <DataRow> list = new List <DataRow>(dtSummary.Select());

                PdfPageSettings pageSettings = new PdfPageSettings(50f);
                pageSettings.Margins.Left = 15;

                pageSettings.Margins.Right = 15;

                pageSettings.Margins.Top = 10;

                pageSettings.Margins.Bottom = 10;

                PdfDocument pdfDocument = exp.Export(Grid1.Model, (IEnumerable)list, "FindDocumentStatus.pdf", true, true, "flat-lime", true);

                RectangleF rect  = new RectangleF(0, 0, pdfDocument.PageSettings.Width, 50);
                RectangleF rect1 = new RectangleF(0, 0, pdfDocument.PageSettings.Width, 50);

                //create a header pager template
                PdfPageTemplateElement header  = new PdfPageTemplateElement(rect);
                PdfPageTemplateElement header1 = new PdfPageTemplateElement(rect1);

                //create a footer pager template
                PdfPageTemplateElement footer = new PdfPageTemplateElement(rect);

                Font f = new Font("Arial", 11, FontStyle.Bold);

                PdfFont font = new PdfTrueTypeFont(f, true);

                //header.Graphics.DrawString("Land Aquisition", font, PdfBrushes.Black, new Point(250, 0)); //Add custom text to the Header
                //pdfDocument.Template.Top = header; //Append custom template to the document

                //header1.Graphics.DrawString("All Family Details", font, PdfBrushes.Black, new Point(0, 3)); //Add custom text to the Header
                //pdfDocument.Template.Top = header1; //Append custom template to the document
                PdfBrush brush = new PdfSolidBrush(Color.Black);
                //Add the fields in composite fields
                PdfCompositeField compositeField  = new PdfCompositeField(font, brush, "Land Aquisition - SEZ Thane");
                PdfCompositeField compositeField1 = new PdfCompositeField(font, brush, "Find Document Status");
                //PdfCompositeField compositeField2 = new PdfCompositeField(font, brush, "Report");
                //PdfCompositeField compositeField3 = new PdfCompositeField(font, brush, "Family Details");
                compositeField.Bounds = header.Bounds;
                //Draw the composite field in footer
                compositeField.Draw(footer.Graphics, new PointF(200, 0));
                compositeField1.Draw(footer.Graphics, new PointF(230, 10));
                //compositeField2.Draw(footer.Graphics, new PointF(205, 20));
                //compositeField3.Draw(footer.Graphics, new PointF(228, 40));
                //Add the footer template at the bottom
                pdfDocument.Template.Top = header;

                footer.Graphics.DrawString("CopyRights", font, PdfBrushes.Gray, new Point(250, 0)); //Add Custom text to footer
                pdfDocument.Template.Bottom = footer;                                               //Add the footer template to document

                pdfDocument.Save("FindDocumentStatus.pdf", Response, HttpReadType.Save);
            }
            else
            {
            }
        }
Пример #18
0
        /// <summary>
        /// Converte url para pdf (limitado apenas para uma página em formato A4)
        /// </summary>
        /// <param name="stringUrl">http://e.migalhas.com.br/payment/2020/03/25/SANTANDER_0236f0078_save.html</param>
        /// <param name="outputFile">byteArray de um pdf</param>
        /// <returns>string base 64 de um pdf</returns>
        public static string ConvertUrlToPdf(string stringUrl, out Byte[] outputFile)
        {
            PdfDocument         pdfDoc              = null;
            PdfPageSettings     pdfPageSetting      = null;
            PdfHtmlLayoutFormat pdfHtmlLayoutFormat = null;
            FileStream          fsOutput            = null;

            byte[] pdfByteArray   = null;
            string stringFilePath = null;
            Thread threadLoadHtml = null;

            try
            {
                pdfDoc = new PdfDocument();
                pdfDoc.ConvertOptions.SetPdfToHtmlOptions(true, true, 1);

                pdfPageSetting             = new PdfPageSettings();
                pdfPageSetting.Size        = PdfPageSize.A4;
                pdfPageSetting.Orientation = PdfPageOrientation.Portrait;
                pdfPageSetting.Margins     = new Spire.Pdf.Graphics.PdfMargins(10);

                pdfHtmlLayoutFormat           = new PdfHtmlLayoutFormat();
                pdfHtmlLayoutFormat.IsWaiting = false; //Não espera a leitura completa da url, se colocar true demora 30s para ler a url. :(
                pdfHtmlLayoutFormat.FitToPage = Clip.Width;
                pdfHtmlLayoutFormat.Layout    = Spire.Pdf.Graphics.PdfLayoutType.OnePage;

                //Faz a leitura em outra thread conforme documentação do componente Spire.Pdf
                threadLoadHtml = new Thread(() =>
                                            { pdfDoc.LoadFromHTML(stringUrl, false, false, false, pdfPageSetting, pdfHtmlLayoutFormat); });
                threadLoadHtml.SetApartmentState(ApartmentState.STA);
                threadLoadHtml.Start();
                threadLoadHtml.Join();

                stringFilePath = AppDomain.CurrentDomain.BaseDirectory + Guid.NewGuid().ToString() + ".pdf";

                fsOutput = new FileStream(stringFilePath, FileMode.CreateNew, FileAccess.ReadWrite);

                pdfDoc.SaveToStream(fsOutput, FileFormat.PDF);

                fsOutput.Close();                                 //Existe uma operação de io neste momento

                pdfByteArray = File.ReadAllBytes(stringFilePath); //Existe uma operação de io neste momento

                File.Delete(stringFilePath);                      //Existe uma operação de io neste momento

                pdfDoc.Close();

                outputFile = pdfByteArray;

                return(Convert.ToBase64String(pdfByteArray));
            }
            catch
            {
                throw; //em caso de erro, joga o erro pra cima
            }
            finally
            {
                pdfDoc              = null;
                pdfPageSetting      = null;
                pdfHtmlLayoutFormat = null;
                fsOutput            = null;
                pdfByteArray        = null;
                stringFilePath      = null;
                threadLoadHtml      = null;
            }
        }
Пример #19
0
        public static byte[] ConvertToPdf(string fileName)
        {
            string       contentType = MimeMapping.GetMimeMapping(fileName);
            MemoryStream mem         = new MemoryStream();

            switch (contentType.ToLower())
            {
            case "image/gif":
            case "image/jpg":
            case "image/png":
            case "image/jpeg":
            case "application/BMP":
            case "image/bmp":
            case "image/tiff":
                if (!string.IsNullOrEmpty(fileName))
                {
                    Document document = new Document(PageSize.LETTER, 10, 10, 10, 10);
                    //using ( var stream = new MemoryStream() )
                    //{
                    PdfWriter.GetInstance(document, mem);

                    document.Open();
                    using (var imageStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                    {
                        var image = Image.GetInstance(imageStream);
                        image.ScaleAbsolute(585, 750);
                        //image.ScaleAbsoluteHeight(PageSize.A4.Height - 20);
                        //image.ScaleToFit(PageSize.LETTER);

                        document.Add(image);
                    }
                    document.Close();

                    // return stream.ToArray();
                    //}
                }

                break;

            case "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":
            case "application/vnd.ms-excel":
            case "application/xlsx":
            case "application/xls":
            case "application/vnd.ms-excel.sheet.macroEnabled.12":
            case "application/XLSM":
                if (!string.IsNullOrEmpty(fileName))
                {
                    Spire.Xls.Workbook workbook = new Spire.Xls.Workbook();
                    workbook.LoadFromFile(fileName, true);
                    workbook.SaveToStream(mem, Spire.Xls.FileFormat.PDF);
                }

                break;

            case "application/vnd.openxmlformats-officedocument.wordprocessingml.document":
            case "application/msword":
            case "application/docx":
            case "application/doc":
                if (!string.IsNullOrEmpty(fileName))
                {
                    Spire.Doc.Document document = new Spire.Doc.Document();
                    document.LoadFromFile(fileName, Spire.Doc.FileFormat.Auto);
                    document.SaveToStream(mem, Spire.Doc.FileFormat.PDF);
                    document.Close();
                }

                break;

            case "application/html":
            case "application/txt":
            case "application/htm":
            case "text/html":
            case "application/xml":
            case "text/plain":
                if (!string.IsNullOrEmpty(fileName))
                {
                    Spire.Pdf.PdfDocument pdf = new Spire.Pdf.PdfDocument();
                    PdfHtmlLayoutFormat   htmlLayoutFormat = new PdfHtmlLayoutFormat
                    {
                        Layout          = PdfLayoutType.Paginate,
                        FitToPage       = Clip.Width,
                        LoadHtmlTimeout = 60 * 1000
                    };
                    htmlLayoutFormat.IsWaiting = true;
                    PdfPageSettings setting = new PdfPageSettings();
                    setting.Size = PdfPageSize.A4;
                    Thread thread = new Thread(() => { pdf.LoadFromHTML(fileName, true, true, true); });
                    thread.SetApartmentState(ApartmentState.STA);
                    thread.Start();
                    thread.Join();
                    pdf.SaveToStream(mem, Spire.Pdf.FileFormat.PDF);
                }
                break;

            case "application/msg":
            case "application/octet-stream":
            case "multipart/related":
            case "application/ZIP":
            case "application/VCF":
            default:
                break;
            }

            return(mem.ToArray());
        }
        private void btnDescargaPdf_Click(object sender, EventArgs e)
        {
            PdfDocument         pdf = new PdfDocument();
            PdfHtmlLayoutFormat htmlLayoutFormat = new PdfHtmlLayoutFormat();

            htmlLayoutFormat.IsWaiting = false;
            PdfPageSettings setting = new PdfPageSettings();

            setting.Size = PdfPageSize.A4;
            Dictionary <string, string> datosFrm = new Dictionary <string, string>();
            UsuarioBLL negocioUsuario            = new UsuarioBLL();

            DAL.VS_Login.VHWServiceClient VHWS = new DAL.VS_Login.VHWServiceClient();

            var resp = VHWS.lstCantidadPermisoEstado().ToList();
            //datosFrm = negocioUsuario.frmPermisoUsuario(1061);
            //string idSolicitud = (new System.Collections.Generic.Mscorlib_DictionaryDebugView<string, string>(datosFrm)).Items[0].Value;
            //string rutFuncionario = (new System.Collections.Generic.Mscorlib_DictionaryDebugView<string, string>(datosFrm)).Items[3].Value;
            //string htmlCode = File.ReadAllText("..\\..\\2.html");
            string htmlCode = @"<h1 style='text-align: center;'><span style='text-decoration: underline;'>Resumen de permisos por unidad interna</span></h1><p>&nbsp;</p>";

            foreach (var item in resp)
            {
                htmlCode = htmlCode + @"<p style='text-align: center;'><em><strong>ID UNIDAD INTERNA: {0}</strong></em></p>
<p style='text-align: center;'>&nbsp;</p>
<p style='text-align: center;'><em><strong>CANTIDAD: {1}</strong></em></p>
<p style='text-align: center;'>&nbsp;</p>
<p style='text-align: center;'><em><strong>RECURSO LEGAL: {2}</strong></em></p>
<p>&nbsp;</p>
<p>&nbsp;</p>";
                htmlCode = string.Format(htmlCode, item.unidadInterna, item.cantidad, item.recursoLegal);
            }

            htmlCode = htmlCode.Replace(System.Environment.NewLine, string.Empty);

            Thread thread = new Thread(() =>
                                       { pdf.LoadFromHTML(htmlCode, false, setting, htmlLayoutFormat); });

            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
            thread.Join();

            SaveFileDialog MyFiles = new SaveFileDialog();

            MyFiles.Filter     = "PDF Files|*.pdf";
            MyFiles.Title      = "GUARDAR COMPROBANTE PERMISO";
            MyFiles.DefaultExt = "*.pdf";
            MyFiles.FileName   = "resumenPermisoUnidadInterna";
            if (MyFiles.ShowDialog() == DialogResult.OK)
            {
                if (File.Exists(MyFiles.FileName))
                {
                    File.Delete(MyFiles.FileName);
                }

                //File.Copy(path, MyFiles.FileName);
                pdf.SaveToFile(MyFiles.FileName);
            }


            //System.Diagnostics.Process.Start("output.pdf");
        }
Пример #21
0
        private void btnVerPermiso_Click(object sender, EventArgs e)
        {
            PdfDocument         pdf = new PdfDocument();
            PdfHtmlLayoutFormat htmlLayoutFormat = new PdfHtmlLayoutFormat();

            htmlLayoutFormat.IsWaiting = false;
            PdfPageSettings setting = new PdfPageSettings();

            setting.Size = PdfPageSize.A4;
            Dictionary <string, string> datosFrm = new Dictionary <string, string>();
            UsuarioBLL negocioUsuario            = new UsuarioBLL();

            datosFrm = negocioUsuario.frmPermisoUsuario(1061);
            //string idSolicitud = (new System.Collections.Generic.Mscorlib_DictionaryDebugView<string, string>(datosFrm)).Items[0].Value;
            //string rutFuncionario = (new System.Collections.Generic.Mscorlib_DictionaryDebugView<string, string>(datosFrm)).Items[3].Value;
            //string htmlCode = File.ReadAllText("..\\..\\2.html");
            string htmlCode = @"<h1 style='text-align: center;'><span style='text-decoration: underline;'>COMPROBANTE PERMISO FUNCIONARIO MUNICIPALIDAD VISTA HERMOSA</span></h1>
<p>&nbsp;</p>
<p style='text-align: center;'><em><strong>ID SOLICITUD: {0}</strong></em></p>
<p style='text-align: center;'>&nbsp;</p>
<p style='text-align: center;'><em><strong>RUT FUNCIONARIO: {1}</strong></em></p>
<p style='text-align: center;'>&nbsp;</p>
<p style='text-align: center;'><em><strong>FECHA INICIO SOLICITUD: {2}</strong></em></p>
<p style='text-align: center;'>&nbsp;</p>
<p style='text-align: center;'><em><strong>FECHA FIN SOLICITUD: {3}</strong></em></p>
<p style='text-align: center;'>&nbsp;</p>
<p style='text-align: center;'><em><strong>MOTIVO SOLICITUD: {4}</strong></em></p>
<p style='text-align: center;'>&nbsp;</p>
<p style='text-align: center;'><em><strong>CODIGO VERIFICACION: {5}</strong></em></p>
<p>&nbsp;</p>
<p>&nbsp;</p>";

            htmlCode = string.Format(htmlCode, datosFrm["idSolicitud"], datosFrm["rutUser"], datosFrm["fechaIni"], datosFrm["fechaFin"], datosFrm["motivo"], datosFrm["idSolicitud"] + datosFrm["rutUser"] + datosFrm["idSolicitud"]);
            // htmlCode = "<strong>ID SOLICITUD: test</strong>";
            htmlCode = htmlCode.Replace(System.Environment.NewLine, string.Empty);

            Thread thread = new Thread(() =>
                                       { pdf.LoadFromHTML(htmlCode, false, setting, htmlLayoutFormat); });

            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
            thread.Join();

            SaveFileDialog MyFiles = new SaveFileDialog();

            MyFiles.Filter     = "PDF Files|*.pdf";
            MyFiles.Title      = "GUARDAR COMPROBANTE PERMISO";
            MyFiles.DefaultExt = "*.pdf";
            MyFiles.FileName   = datosFrm["rutUser"] + "_" + datosFrm["idSolicitud"];
            if (MyFiles.ShowDialog() == DialogResult.OK)
            {
                if (File.Exists(MyFiles.FileName))
                {
                    File.Delete(MyFiles.FileName);
                }

                //File.Copy(path, MyFiles.FileName);
                pdf.SaveToFile(MyFiles.FileName);
            }


            //System.Diagnostics.Process.Start("output.pdf");
        }