Exemple #1
0
        private static bool GeneratePdf(string htmlText, string fileFullName, string watermarkText, PdfFont font)
        {
            if (string.IsNullOrEmpty(htmlText))
            {
                return(false);
            }

            htmlText = "<p>" + htmlText + "</p>";

            var document = new Document();
            var writer   = PdfWriter.GetInstance(document, new FileStream(fileFullName, FileMode.Create));

            if (!string.IsNullOrEmpty(watermarkText))
            {
                writer.PageEvent = new PdfWatermarkPageEvent(watermarkText);
            }

            document.Open();

            //pipeline
            var htmlContext = new HtmlPipelineContext(null);

            htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
            htmlContext.SetImageProvider(new ChannelImageProvider());

            htmlContext.SetCssAppliers(new CssAppliersImpl(GetFontProviderBy(font)));
            var cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(true);
            var pipeline    = new CssResolverPipeline(cssResolver,
                                                      new HtmlPipeline(htmlContext, new PdfWriterPipeline(document, writer)));

            //parse
            byte[] data    = Encoding.UTF8.GetBytes(htmlText);
            var    msInput = new MemoryStream(data);
            var    worker  = new XMLWorker(pipeline, true);
            var    parser  = new XMLParser(worker);

            parser.Parse(msInput); //XMLWorkerHelper.GetInstance().ParseXHtml(..)
            var pdfDest = new PdfDestination(PdfDestination.XYZ, 0, document.PageSize.Height, 1f);
            var action  = PdfAction.GotoLocalPage(1, pdfDest, writer);

            writer.SetOpenAction(action);

            //close
            document.Close();
            msInput.Close();

            return(true);
        }