本文介绍了下载HTML文件作为PDF abcpdf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何可以下载一个HTML文件,如ASP.Net使用abcpdf一个PDF,C#?

How can I download an HTML file as a PDF using abcpdf in ASP.Net, C#?

推荐答案

此方法适用于我们的项目

This method works well in our project

    /// <summary>
    /// Converts Html to pdf
    /// </summary>
    /// <param name="htmlOrUrl">Html markup of html page URL</param>
    /// <param name="isUrl">previous parameter is URL</param>
    /// <param name="highQuality">use high quality converter engine</param>
    /// <param name="indent">indent from all sides of the page</param>
    /// <returns>Memory stream with PDF-file</returns>
    public static MemoryStream HtmlToPDF(this String htmlOrUrl, Boolean isUrl, Boolean highQuality = false, Int32 indent = 20)
    {
        using (var doc = new Doc())
        {
            doc.Color.String = "0, 0, 0";
            doc.HtmlOptions.UseScript = true;
            doc.HtmlOptions.AddLinks = true;
            if (highQuality)
            {
                doc.HtmlOptions.Engine = EngineType.Gecko;
            }

            // 1. CONTENT BLOCK
            doc.Rect.Left = 0 + indent;
            doc.Rect.Top = 792 - indent;
            doc.Rect.Right = 612 - indent;
            doc.Rect.Bottom = 0 + indent;

            doc.AppendChainable(htmlOrUrl, isUrl);

            var ms = new MemoryStream();
            doc.Save(ms);
            if (ms.CanSeek)
            {
                ms.Seek(0, SeekOrigin.Begin);
            }
            return ms;
        }
    }

    /// <summary>
    /// Appends document with multipage content 
    /// </summary>
    private static void AppendChainable(this Doc doc, String htmlOrUrl, Boolean isUrl = false)
    {
        Int32 blockId = isUrl 
            ? doc.AddImageUrl(htmlOrUrl) 
            : doc.AddImageHtml(String.Format(HtmlWrapper, htmlOrUrl));

        while (doc.Chainable(blockId))
        {
            //doc.FrameRect(); // add a black border
            doc.Page = doc.AddPage();
            blockId = doc.AddImageToChain(blockId);
        }
    }

//使用

var testMs1 = ABCPdfConverter.ABCConverter.HtmlToPDF("https://developers.google.com
   /chart/interactive/docs/examples", true, false, 20);
testMs1.StreamToFile(@"D:/3.pdf");

//和流以文件为

// and Stream to file is

/// <summary>
/// Saves stream instance to file
/// </summary>
public static void StreamToFile(this MemoryStream input, String outputFileName)
{
    var dirName = Path.GetDirectoryName(outputFileName);
    var fileName = Path.GetFileName(outputFileName);
    if (String.IsNullOrEmpty(dirName) || String.IsNullOrWhiteSpace(fileName))
    {
        throw new IOException("outputFileName");
    }

    using (FileStream outStream = File.Create(outputFileName))
    {
        input.WriteTo(outStream);
        outStream.Flush();
        outStream.Close();
    }
}

这篇关于下载HTML文件作为PDF abcpdf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-24 20:21