Exemplo n.º 1
0
        public void ManipulatePdf(string htmlSource, string pdfDest, string resourceLoc, PageSize pageSize, float screenWidth)
        {
            PdfWriter   writer = new PdfWriter(pdfDest);
            PdfDocument pdfDoc = new PdfDocument(writer);

            // Set the result to be tagged
            pdfDoc.SetTagged();
            pdfDoc.SetDefaultPageSize(pageSize);

            ConverterProperties converterProperties = new ConverterProperties();

            // Set media device description details
            MediaDeviceDescription mediaDescription = new MediaDeviceDescription(MediaType.SCREEN);

            mediaDescription.SetWidth(screenWidth);
            converterProperties.SetMediaDeviceDescription(mediaDescription);

            FontProvider fp = new DefaultFontProvider();

            // Register external font directory
            fp.AddDirectory(resourceLoc);

            converterProperties.SetFontProvider(fp);
            // Base URI is required to resolve the path to source files
            converterProperties.SetBaseUri(resourceLoc);

            // Create acroforms from text and button input fields
            converterProperties.SetCreateAcroForm(true);

            HtmlConverter.ConvertToPdf(new FileStream(htmlSource, FileMode.Open, FileAccess.Read, FileShare.Read),
                                       pdfDoc, converterProperties);

            pdfDoc.Close();
        }
Exemplo n.º 2
0
        public virtual void TestThatAddedFontIsReleasedAfterConversion()
        {
            // TODO unignore after DEVSIX-3199 is fixed
            String dirName        = "AddedFontIsReleased/";
            String htmlFileName   = "addedFontIsReleased.html";
            String fontFileName   = "NotoSans-Regular.ttf";
            String sourceHtmlFile = sourceFolder + dirName + htmlFileName;
            String sourceFontFile = sourceFolder + dirName + fontFileName;
            String workDir        = destinationFolder + dirName;

            CreateDestinationFolder(workDir);
            String targetPdfFile   = workDir + "target.pdf";
            String workDirFontFile = workDir + fontFileName;

            File.Copy(Path.Combine(sourceFontFile), Path.Combine(workDirFontFile));
            DefaultFontProvider fontProvider = new DefaultFontProvider(true, false, false);

            fontProvider.AddDirectory(workDir);
            ConverterProperties properties = new ConverterProperties().SetBaseUri(sourceFolder).SetFontProvider(fontProvider
                                                                                                                );

            HtmlConverter.ConvertToPdf(new FileInfo(sourceHtmlFile), new FileInfo(targetPdfFile), properties);
            FileInfo resourceToBeRemoved = new FileInfo(workDirFontFile);

            FileUtil.DeleteFile(resourceToBeRemoved);
            NUnit.Framework.Assert.IsFalse(resourceToBeRemoved.Exists);
        }
Exemplo n.º 3
0
        public MemoryStream ManipulatePdf(PageSize pageSize)
        {
            var memoryStream = new MemoryStream();

            var properties          = new ConverterProperties();
            var defaultFontProvider = new DefaultFontProvider(true, true, false);

            defaultFontProvider.AddDirectory(FONT_DIRECTORY);
            properties.SetFontProvider(defaultFontProvider);

            using (var pdfWriter = new PdfWriter(memoryStream))
            {
                pdfWriter.SetCloseStream(false);
                var pdfDocument = new PdfDocument(pdfWriter);
                pdfDocument.SetDefaultPageSize(pageSize);

                if (!string.IsNullOrEmpty(_convertRequest.Header))
                {
                    var headerHandler = new ReportHeaderCreator(_convertRequest.Header);
                    pdfDocument.AddEventHandler(PdfDocumentEvent.START_PAGE, headerHandler);
                }

                if (!string.IsNullOrEmpty(_convertRequest.Footer))
                {
                    var footerHandler = new ReportFooterCreator(_convertRequest.Footer);
                    pdfDocument.AddEventHandler(PdfDocumentEvent.END_PAGE, footerHandler);
                }

                var document = HtmlConverter.ConvertToDocument(_convertRequest.Content, pdfDocument, properties);
                document.Close();
            }

            memoryStream.Position = 0;
            return(memoryStream);
        }
Exemplo n.º 4
0
        public void ManipulatePdf(string htmlSource, string pdfDest)
        {
            PdfWriter   writer = new PdfWriter(pdfDest);
            PdfDocument pdfDoc = new PdfDocument(writer);

            // Default provider will register standard fonts and free fonts shipped with iText, but not system fonts
            FontProvider provider = new DefaultFontProvider();

            // 1. Register all fonts in a directory
            provider.AddDirectory(FONT_FOLDER);

            // 2. Register a single font by specifying path
            provider.AddFont(FONT1);

            // 3. Use the raw bytes of the font file
            byte[] fontBytes = File.ReadAllBytes(FONT2);
            provider.AddFont(fontBytes);

            // Make sure the provider is used
            ConverterProperties converterProperties = new ConverterProperties()
                                                      // Base URI is required to resolve the path to source files
                                                      .SetBaseUri(SRC)
                                                      .SetFontProvider(provider);

            HtmlConverter.ConvertToPdf(new FileStream(htmlSource, FileMode.Open), pdfDoc, converterProperties);

            pdfDoc.Close();
        }
Exemplo n.º 5
0
            public virtual void HandleEvent(Event @event)
            {
                var docEvent = (PdfDocumentEvent)@event;
                var pdf      = docEvent.GetDocument();

                var page     = docEvent.GetPage();
                var pageSize = page.GetPageSize();


                var   coordX       = pageSize.GetWidth() / 2;
                float coordY       = PdfFormation.PAGE_NUMBER_FOOTER_MARGIN_BOTTOM;
                var   canvasWidth  = pageSize.GetWidth();
                float canvasHeight = PdfFormation.PAGE_NUMBER_FOOTER_HEIGHT;

                var canvas = new Canvas(new PdfCanvas(page), new Rectangle(coordX, coordY, canvasWidth, canvasHeight));

                canvas.SetFontProvider(new DefaultFontProvider(true, true, true));
                canvas.SetFontSize(REGULAR_FONT_SIZE);
                canvas.SetFont(PdfFontFactory.CreateFont(FONT_TIMES_NEW_ROMAN));

                var pageFooter = _footer.Replace(PdfFormation.PAGE_NUMBER_TEMPLATE, pdf.GetPageNumber(page).ToString());

                var properties          = new ConverterProperties();
                var defaultFontProvider = new DefaultFontProvider(true, true, true);

                defaultFontProvider.AddDirectory(FONT_DIRECTORY);
                properties.SetFontProvider(defaultFontProvider);

                foreach (var element in HtmlConverter.ConvertToElements(pageFooter, properties))
                {
                    canvas.Add((IBlockElement)element);
                }

                canvas.Close();
            }
Exemplo n.º 6
0
        /// <summary>
        /// Creates the PDF file.
        /// </summary>
        /// <param name="src">the path to the source HTML file</param>
        /// <param name="fonts">the path to a font folder with extra fonts</param>
        /// <param name="dest">the path to the resulting PDF</param>
        public void CreatePdf(String src, String fonts, String dest)
        {
            ConverterProperties properties   = new ConverterProperties();
            FontProvider        fontProvider = new DefaultFontProvider();

            fontProvider.AddDirectory(fonts);
            properties.SetFontProvider(fontProvider);
            HtmlConverter.ConvertToPdf(new FileInfo(src), new FileInfo(dest), properties);
        }
Exemplo n.º 7
0
        /// <summary>
        /// Creates the PDF file.
        /// </summary>
        /// <param name="src">the path to the source HTML file</param>
        /// <param name="fonts">the path to a folder containing a series of fonts</param>
        /// <param name="dest">the path to the resulting PDF</param>
        public void CreatePdf(String src, String fonts, String dest)
        {
            PdfWriter   writer = new PdfWriter(dest);
            PdfDocument pdf    = new PdfDocument(writer);

            pdf.SetDefaultPageSize(PageSize.A4.Rotate());
            ConverterProperties properties   = new ConverterProperties();
            FontProvider        fontProvider = new DefaultFontProvider(false, false, false);

            fontProvider.AddDirectory(fonts);
            properties.SetFontProvider(fontProvider);
            HtmlConverter.ConvertToPdf(new FileStream(src, FileMode.Open, FileAccess.Read), pdf, properties);
        }
Exemplo n.º 8
0
        public virtual void BatchConversionTest()
        {
            ConverterProperties properties = new ConverterProperties().SetBaseUri(sourceFolder).SetMediaDeviceDescription
                                                 (new MediaDeviceDescription(MediaType.PRINT));
            FontProvider fontProvider = new DefaultFontProvider(true, false, false);

            fontProvider.AddDirectory(sourceFolder + "fonts/");
            properties.SetFontProvider(fontProvider);
            IHtmlProcessor processor   = new DefaultHtmlProcessor(properties);
            IXmlParser     parser      = new JsoupHtmlParser();
            String         outPdfPath  = destinationFolder + "smashing1.pdf";
            PdfDocument    pdfDocument = new PdfDocument(new PdfWriter(outPdfPath));
            IDocumentNode  doc         = parser.Parse(new FileStream(sourceFolder + "smashing01.html", FileMode.Open, FileAccess.Read
                                                                     ), properties.GetCharset());
            Document document = processor.ProcessDocument(doc, pdfDocument);

            document.Close();
            NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outPdfPath, sourceFolder + "cmp_smashing1.pdf"
                                                                             , destinationFolder, "diff01_"));
        }
Exemplo n.º 9
0
        public void ManipulatePdf(String htmlSource, String pdfDest, String freeFontsDirectory)
        {
            // In pdfHTML the iText layouting mechanism now works in HTML rendering mode. In order
            // to switch to the iText default rendering mode, you should declare a custom ICssApplierFactory
            // in which to create a custom ICssApplier for the body node. Then set the default rendering mode
            // property for the property container.
            ICssApplierFactory customCssApplierFactory = new DefaultModeCssApplierFactory();

            // Starting from pdfHTML version 3.0.0 the GNU Free Fonts family (e.g. FreeSans) that were shipped together with the pdfHTML distribution
            // are now replaced by Noto fonts. If your HTML file contains characters which are not supported by standard PDF fonts (basically most of the
            // characters except latin script and some of the symbol characters, e.g. cyrillic characters like in this sample) and also if no other fonts
            // are specified explicitly by means of iText `FontProvider` class or CSS `@font-face` rule, then pdfHTML shipped fonts covering a wide range
            // of glyphs are used instead. In order to replicate old behavior, one needs to exclude from `FontProvider` the fonts shipped by default and
            // provide GNU Free Fonts instead. GNU Free Fonts can be found at https://www.gnu.org/software/freefont/.
            FontProvider fontProvider = new DefaultFontProvider(true, false, false);

            fontProvider.AddDirectory(freeFontsDirectory);

            ConverterProperties converterProperties = new ConverterProperties()
                                                      .SetBaseUri(freeFontsDirectory)
                                                      // Try removing registering of custom DefaultModeCssApplierFactory to compare legacy behavior
                                                      // with the newly introduced. You would notice that now lines spacing algorithm is changed:
                                                      // line spacing is considerably smaller and is closer compared to browsers rendering.
                                                      // You would also notice that now single image in a line behaves according to HTML's "noQuirks" mode:
                                                      // there's an additional "spacing" underneath the image which depends on element's `line-height` and
                                                      // `font-size` CSS properties.
                                                      .SetCssApplierFactory(customCssApplierFactory)
                                                      .SetFontProvider(fontProvider);

            // When converting using the method #convertToElements to change the rendering mode you must also
            // use the flag Property.RENDERING_MODE. However it must be added to the elements from the
            // resulting list before adding these elements to the document. Then the elements will be
            // placed in the specified mode.
            HtmlConverter.ConvertToPdf(new FileStream(htmlSource, FileMode.Open, FileAccess.Read),
                                       new FileStream(pdfDest, FileMode.Create), converterProperties);
        }
Exemplo n.º 10
0
        public async Task <IActionResult> Convert()
        {
            StringValues clientParam;
            StringValues keyParam;
            StringValues orientationParam;
            StringValues pageSizeParam;
            var          hasClient      = Request.Query.TryGetValue("client", out clientParam);
            var          hasKey         = Request.Query.TryGetValue("key", out keyParam);
            var          hasOrientation = Request.Query.TryGetValue("orientation", out orientationParam);
            var          hasPageSize    = Request.Query.TryGetValue("pageSize", out pageSizeParam);
            var          client         = hasClient && clientParam.Count > 0 ? clientParam[0] : "";
            var          key            = hasKey && keyParam.Count > 0 ? keyParam[0] : "";
            var          orientation    = hasOrientation && orientationParam.Count > 0 ? orientationParam[0] : "portrait";
            var          pageSize       = hasPageSize && pageSizeParam.Count > 0 ? pageSizeParam[0] : "A4";

            if (!_clientKeys.ContainsKey(client) || _clientKeys[client] != key)
            {
                return(new NotFoundResult());
            }

            var formData = HttpContext.Request.Form;
            var files    = formData.Files;
            var docFile  = files.Where(f => f.FileName == "doc.html").FirstOrDefault();

            IActionResult response = null;

            if (docFile != null)
            {
                var tempFolder = $"{System.IO.Path.GetTempPath()}{Guid.NewGuid()}";
                Directory.CreateDirectory(tempFolder);

                foreach (var file in files)
                {
                    if (file.FileName != "doc.html")
                    {
                        await System.IO.File.WriteAllBytesAsync($"{tempFolder}/{file.FileName}", ReadAllBytes(file.OpenReadStream()));
                    }
                }

                try
                {
                    using (var htmlSource = docFile.OpenReadStream())
                        using (var pdfDest = new ByteArrayOutputStream())
                        {
                            var writer = new PdfWriter(pdfDest);
                            var pdfDoc = new PdfDocument(writer);
                            pdfDoc.SetTagged();

                            PageSize ps = PageSize.A4;

                            if (pageSize == "A3")
                            {
                                ps = PageSize.A3;
                            }

                            if (orientation == "landscape")
                            {
                                ps = ps.Rotate();
                            }

                            pdfDoc.SetDefaultPageSize(ps);

                            var converterProperties = new ConverterProperties();

                            var fp = new DefaultFontProvider();
                            fp.AddDirectory(tempFolder);
                            converterProperties.SetFontProvider(fp);

                            converterProperties.SetImmediateFlush(true);
                            converterProperties.SetBaseUri(new Uri(tempFolder).AbsoluteUri);
                            HtmlConverter.ConvertToPdf(htmlSource, pdfDoc, converterProperties);
                            var bytes = pdfDest.ToArray();
                            response = new FileContentResult(bytes, "application/pdf");
                        }
                }
                catch (Exception ex)
                {
                    response = StatusCode(500, new { error = ex.Message, stackTrace = ex.StackTrace });
                }

                Directory.Delete(tempFolder, true);
            }
            else
            {
                response = StatusCode((int)HttpStatusCode.BadRequest, new { error = "No doc file provided" });
            }

            return(response);
        }