public byte[] Render(string htmlText, string pageTitle)
        {
            byte[] renderedBuffer;

            using (var outputMemoryStream = new MemoryStream())
            {
                using (var pdfDocument = new Document(PageSize.A4, HorizontalMargin, HorizontalMargin, VerticalMargin, VerticalMargin))
                {
                    string arialuniTff = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "ARIALUNI.TTF");
                    FontFactory.Register(arialuniTff);

                    PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDocument, outputMemoryStream);

                    pdfWriter.CloseStream = false;
                    pdfWriter.PageEvent = new PrintHeaderFooter { Title = pageTitle };
                    pdfDocument.Open();

                    using (var htmlViewReader = new StringReader(htmlText))
                    {
                        using (var htmlWorker = new HTMLWorker(pdfDocument))
                        {
                            StyleSheet styleSheet = new StyleSheet();
                            styleSheet.LoadTagStyle(HtmlTags.BODY, HtmlTags.FACE, "Arial Unicode MS");
                            styleSheet.LoadTagStyle(HtmlTags.BODY, HtmlTags.ENCODING, BaseFont.IDENTITY_H);
                            htmlWorker.SetStyleSheet(styleSheet);
                            htmlWorker.Parse(htmlViewReader);
                        }
                    }
                }

                renderedBuffer = new byte[outputMemoryStream.Position];
                outputMemoryStream.Position = 0;
                outputMemoryStream.Read(renderedBuffer, 0, renderedBuffer.Length);
            }

            return renderedBuffer;
        }
    // Versão Original em: https://social.msdn.microsoft.com/Forums/pt-BR/049133ce-2ce0-4b6e-9194-53b62e12ddbe/como-gerar-um-arquivo-pdf-a-partir-de-uma-pagina-aspx?forum=aspnetpt
    private void ConverteAspx2Pdf()
    {
        // Limpa qualquer coisa já previamente renderizada!
        Response.ClearContent();
        // Para fazer download direto é só descomentar a linha abaixo, caso contrario o PDF é exibido no navegador
        // Response.AddHeader("content-disposition", "attachment; filename=ExportacaoAspx2Pdf.pdf"); 
        
        // Altera o tipo de documento
        Response.ContentType = "application/pdf";

        // Prepara um buffer que conterá todo o HTML que é renderizado
        StringWriter stw = new StringWriter();
        HtmlTextWriter htextw = new HtmlTextWriter(stw);

        // Renderiza todo o HTML do ASPX no buffer (string)
        this.RenderControl(htextw);

        // Cria um novo documento PDF em branco
        Document doc = new Document(PageSize.A4, 10f, 10f, 10f, 10f);

        // Define o local de saida (gravação) do PDF como o dispositivo de transmissão do ASP.Net que vai para o navegador
        PdfWriter.GetInstance(doc, Response.OutputStream);
        doc.Open();

        // Os estilos do boleto devem ser definidos desta forma
        // http://stackoverflow.com/questions/8414637/itextsharp-htmlworker-parsehtml-tablestyle-and-pdfstamper
        
        StyleSheet styles = new StyleSheet();

        Dictionary<string, string> BolCell = new Dictionary<string, string>();
        //styles.LoadStyle("BolCell", "size", "7px");
        BolCell.Add("size", "7pt");
        //BolCell.Add("face", "verdana");
        styles.LoadStyle("BolCell", BolCell);

        Dictionary<string, string> BolField = new Dictionary<string, string>();
        styles.LoadStyle("BolField", "size", "12px");
        //BolField.Add("weight", "bold");
        BolField.Add("size", "9pt");
        //BolField.Add("face", "arial");
        styles.LoadStyle("BolField", BolField);

        // Lê o HTML completo do buffer como uma String
        StringReader str = new StringReader(stw.ToString());

        // Chama um conversor interno de HTML para PDF
        HTMLWorker htmlworker = new HTMLWorker(doc);

        // Transforma o HTML em PDF
        htmlworker.SetStyleSheet(styles);
        htmlworker.Parse(str);

        // fim do PDF
        doc.Close();

        // Transmite o HTML para o browser
        Response.Write(doc);

        // Finaliza tudo! 
        Response.End();
    }
示例#3
0
        public string HTMLToPdfExportBackupReceiptExcel(string HTML, string FilePath)
        {
            FilePath = FilePath.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Millisecond.ToString();
                Document document = new Document();
                try
                {
                    PdfWriter.GetInstance(document, new FileStream(System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "\\PDF\\Temp\\" + FilePath.ToString() + ".pdf", FileMode.Create));
                }
                catch (IOException ex)
                {
                    PdfWriter.GetInstance(document, new FileStream(System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "\\PDF\\Temp\\" + FilePath.ToString() + ".pdf", FileMode.Create));
                }
                document.Open();
                //iTextSharp.text.Image pdfImage = iTextSharp.text.Image.GetInstance(System.Web.HttpContext.Current.Server.MapPath("~/Images/logo.png"));
                //pdfImage.ScaleToFit(200, 200);
                //pdfImage.Alignment = iTextSharp.text.Image.UNDERLYING;
                //pdfImage.SetAbsolutePosition(20, 730);

                //iTextSharp.text.Image pdfsign = iTextSharp.text.Image.GetInstance(System.Web.HttpContext.Current.Server.MapPath("~/Images/sign.png"));
                //pdfsign.ScaleToFit(150, 150);
                //pdfsign.Alignment = iTextSharp.text.Image.ALIGN_BOTTOM;
                //pdfsign.SetAbsolutePosition(400, 365);

                //  document.Add(pdfImage);
                // document.Add(pdfsign);

                iTextSharp.text.html.simpleparser.StyleSheet styles = new iTextSharp.text.html.simpleparser.StyleSheet();

                iTextSharp.text.html.simpleparser.HTMLWorker hw = new iTextSharp.text.html.simpleparser.HTMLWorker(document);
                hw.SetStyleSheet(styles);
                hw.Parse(new StringReader(HTML));
                document.Close();
                document.Dispose();
                return FilePath + ".pdf";
        }