Ejemplo n.º 1
0
        public void Convert(string htmlString, string filePath)
        {
            try
            {
                IConverter converter = new StandardConverter(new PdfToolset(new WinAnyCPUEmbeddedDeployment(new TempFolderDeployment())));

                var document = new HtmlToPdfDocument
                {
                    GlobalSettings =
                    {
                        ProduceOutline = true
                    },
                    Objects =
                    {
                        new ObjectSettings
                        {
                            HtmlText = htmlString
                        }
                    }
                };

                byte[] bytes = converter.Convert(document);
                File.WriteAllBytes(filePath, bytes);
            }
            catch (Exception e)
            {
                throw new Exception("An error occured while converting HTML to PDF. " + e.Message);
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Elaborate
        /// </summary>
        /// <param name="tenantId"></param>
        /// <param name="jobId"></param>
        /// <returns></returns>
        public String Run(String tenantId, String jobId)
        {
            Logger.DebugFormat("Converting {0} to pdf", jobId);
            var localFileName  = DownloadLocalCopy(tenantId, jobId);
            var outputFileName = localFileName + ".pdf";
            var uri            = new Uri(localFileName);

            var document = new HtmlToPdfDocument
            {
                GlobalSettings =
                {
                    ProduceOutline = ProduceOutline,
                    PaperSize      = PaperKind.A4, // Implicit conversion to PechkinPaperSize
                    Margins        =
                    {
                        All  =          1.375,
                        Unit = Unit.Centimeters
                    },
                    OutputFormat   = GlobalSettings.DocumentOutputFormat.PDF
                },
                Objects =
                {
                    new ObjectSettings
                    {
                        PageUrl     = uri.AbsoluteUri,
                        WebSettings = new WebSettings()
                        {
                            EnableJavascript = false,
                            PrintMediaType   = false
                        }
                    },
                }
            };
            //This is the thread safe converter
            //it seems sometimes to hang forever during tests.
            //https://github.com/tuespetre/TuesPechkin
            //IConverter converter =
            //     new ThreadSafeConverter(
            //         new PdfToolset(
            //             new Win32EmbeddedDeployment(
            //                 new TempFolderDeployment())));

            //Standard, non thread safe converter.
            IConverter converter =
                new StandardConverter(
                    new PdfToolset(
                        new Win32EmbeddedDeployment(
                            new TempFolderDeployment())));

            var pdf = converter.Convert(document);

            File.WriteAllBytes(outputFileName, pdf);

            Logger.DebugFormat("Deleting {0}", localFileName);
            File.Delete(localFileName);
            Logger.DebugFormat("Conversion of {0} to pdf done!", jobId);

            return(outputFileName);
        }
Ejemplo n.º 3
0
        public void ConvertsToCorrectType(Type type, string val, object expectedConvertedVal)
        {
            // Arrange.
            IConverter converter = new StandardConverter();

            // Act.
            object result;
            bool   converted = converter.TryConvertTo(type, val, out result);

            // Assert.
            Assert.True(converted);
            Assert.IsType(type, result);
            Assert.Equal(result, expectedConvertedVal);
        }
Ejemplo n.º 4
0
        public Console(StandardConverter tempConverter,
                       NoFocusTrackBar trackBar)
        {
            _fahrenheitPainter = new PanelPainter();
            _celsiusPainter    = new PanelPainter();
            _kelvinPainter     = new PanelPainter();

            _tempConverter = tempConverter;
            _trackBar      = trackBar;

            InitializeComponent();
            InitAndDisplayTrackBar();
            InitialiseScaleLabels();
            CreateLabelToolTips();
        }
Ejemplo n.º 5
0
        private void SaveHtmlAsPdf(string fName, string html)
        {
            var document = new HtmlToPdfDocument
            {
                GlobalSettings =
                {
                    ProduceOutline = true,
                    DocumentTitle  = "Pretty Websites",
                    PaperSize      = PaperKind.A4,
                    Margins        =
                    {
                        All  =             1.375,
                        Unit = Unit.Centimeters
                    },
                },
                Objects =
                {
                    new ObjectSettings {
                        HtmlText    = "<html><head><style>html * { font-family: Arial !important; }</style><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"><title></title></head><body>" + html + "</body></html>",
                        WebSettings = new WebSettings()
                        {
                            LoadImages      = true,
                            PrintBackground = true
                        },
                        ProduceExternalLinks = true,
                        LoadSettings         = new LoadSettings()
                        {
                            BlockLocalFileAccess = false,
                            StopSlowScript       = false
                        }
                    }
                }
            };

            IConverter converter = new StandardConverter(new PdfToolset(new StaticDeployment(Application.StartupPath)));

            byte[] pdfBuf = converter.Convert(document);

            FileStream fs = new FileStream(fName, FileMode.Create, FileAccess.ReadWrite);

            foreach (var byteSymbol in pdfBuf)
            {
                fs.WriteByte(byteSymbol);
            }
            fs.Close();
        }
Ejemplo n.º 6
0
        public ActionResult CreatePdf()
        {
            int i_customer_id = (int)Session["icustomer_id"];
            int i_year        = (int)Session["iyear"];
            int i_month       = (int)Session["imonth"];

            var helper   = new UrlHelper(ControllerContext.RequestContext);
            var indexUrl = helper.Action("IndexPDF", "invoice_detail", new { i_customer_id = i_customer_id, i_year = i_year, i_month = i_month }, Request.Url.Scheme);

            var document = new HtmlToPdfDocument()
            {
                GlobalSettings =
                {
                    ProduceOutline = true,
                    DocumentTitle  = "PDF Sample",
                    PaperSize      = PaperKind.A4,
                    Margins        =
                    {
                        All  =        1.375,
                        Unit = Unit.Centimeters
                    }
                },
                Objects =
                {
                    new ObjectSettings()
                    {
                        PageUrl = indexUrl,
                    },
                }
            };

            var converter = new StandardConverter(
                new PdfToolset(
                    new WinAnyCPUEmbeddedDeployment(
                        new TempFolderDeployment()
                        )
                    )
                );

            var pdfData = converter.Convert(document);

            return(File(pdfData, "application/pdf", "PdfSample.pdf"));
        }
Ejemplo n.º 7
0
        internal static void Main()
        {
            //For UI thread exceptions
            Application.ThreadException += GlobalExceptionHandler;

            //Force all Windows Forms errors to go through our handler
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

            //For non-UI thread exceptions
            AppDomain.CurrentDomain.UnhandledException += GlobalExceptionHandler;

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

            var tempConverter   = new StandardConverter();
            var noFocusTrackBar = new NoFocusTrackBar(new Scale <int>(minimum: -220, maximum: 220, scaleBy: 5));

            Application.Run(new Console(tempConverter, noFocusTrackBar));
        }
Ejemplo n.º 8
0
        public ActionResult About()
        {
            var helper   = new UrlHelper(ControllerContext.RequestContext);
            var indexUrl = helper.Action("Index", "Home", null, Request.Url.Scheme);

            var document = new HtmlToPdfDocument()
            {
                GlobalSettings =
                {
                    ProduceOutline = true,
                    DocumentTitle  = "PDF Sample",
                    PaperSize      = PaperKind.A4,
                    Margins        =
                    {
                        All  =        1.375,
                        Unit = Unit.Centimeters
                    }
                },
                Objects =
                {
                    new ObjectSettings()
                    {
                        PageUrl = indexUrl,
                    },
                }
            };

            var converter = new StandardConverter(
                new PdfToolset(
                    new WinAnyCPUEmbeddedDeployment(
                        new TempFolderDeployment())));

            var pdfData = converter.Convert(document);

            return(File(pdfData, "application/pdf", "PdfSample.pdf"));
        }
Ejemplo n.º 9
0
    /// <summary>
    /// Faz a impressão de uma página HTML de nota de Itapema para PDF e salva ela em um arquivo no diretório "DiretorioDestinoDownload".
    /// Essa rotina faz também as buscas das imagens do HTML para mostrar a página no PDF como ela é exibida para o usuário.
    /// </summary>
    /// <param name="URL">Link da página da nota.</param>
    /// <param name="contador">Contador de qual nota está atualmente. Será inserido no nome do arquivo.</param>
    public void imprimePaginaParaPDF(string URL, int contador)
    {
        this.Request(URL);

        #region Busca das imagens para inserção no HTML retornado.
        string html = this.ResponseDataText;
        HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
        doc.LoadHtml(html);
        HtmlNodeCollection imagens = doc.DocumentNode.SelectNodes("//img[@src]");
        foreach (HtmlNode imagem in imagens)
        {
            string linkDownload = imagem.GetAttributeValue("src", "");
            if (linkDownload != "")
            {
                string imagemb64 = "";
                //Se a imagem já foi baixada vai estar em cache. Senão faz o download dela e transforma ela em base64.
                if (this.cacheImagens.ContainsKey("https://itapema-sc.prefeituramoderna.com.br/meuiss_new/nfe/" + linkDownload))
                {
                    this.cacheImagens.TryGetValue("https://itapema-sc.prefeituramoderna.com.br/meuiss_new/nfe/" + linkDownload, out imagemb64);
                }
                else
                {
                    this.Request("https://itapema-sc.prefeituramoderna.com.br/meuiss_new/nfe/" + linkDownload);
                    this.ResponseDataStream.Seek(0, 0);

                    imagemb64 = Convert.ToBase64String(this.ResponseDataStream.ToArray());

                    this.cacheImagens.Add("https://itapema-sc.prefeituramoderna.com.br/meuiss_new/nfe/" + linkDownload, imagemb64);
                }

                //Insere o base64 da imagem no HTML.
                imagem.SetAttributeValue("src", "data:image/png;base64," + imagemb64);
            }
        }
        #endregion

        //Atualiza o HTML na variável html.
        StringWriter tx = new StringWriter();
        doc.Save(tx);
        html = tx.ToString();

        #region Impressao do HTML para PDF usando o componente TuesPeckin (https://github.com/tuespetre/TuesPechkin)
        var document = new HtmlToPdfDocument
        {
            GlobalSettings =
            {
                ProduceOutline = true,
                DocumentTitle  = "Nota Itapema",
                PaperSize      = PaperKind.A4,        // Implicit conversion to PechkinPaperSize
                Margins        =
                {
                    All  =          1.375,
                    Unit = Unit.Centimeters
                }
            },
            Objects =
            {
                new ObjectSettings {
                    HtmlText = html
                }
            }
        };

        IConverter converter = new StandardConverter(new PdfToolset(new Win32EmbeddedDeployment(new TempFolderDeployment())));

        byte[] result = converter.Convert(document);
        #endregion

        //Salvando o arquivo obtido.
        Directory.CreateDirectory(this.DiretorioDestinoDownload);
        FileStream fs = new FileStream(Path.Combine(this.DiretorioDestinoDownload, DateTime.Now.ToString("hhmmss_ddmmyyyy") + "_" + contador.ToString() + ".pdf"), FileMode.Create, FileAccess.ReadWrite);
        fs.Write(result, 0, result.Length);
        fs.Close();
    }