使用WebAPI控制器打印为PDF [英] Print to PDF using WebAPI Controller

查看:189
本文介绍了使用WebAPI控制器打印为PDF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要打印当前页"转换为PDF.

I want to print "Current Page" to PDF.

我想使用  Visual Studio的WebAPI控制器.因此,在通过JavaScript调用控制器类的Action方法时,它应该打印当前页面.

I want to do this using  WebAPI Controller of visual studio. So that, on calling the Action method of the controller class via JavaScript , it should print the current page.

我已经编写了代码,但是当我通过点击url调用控制器类时( http://localhost:61045/api/测试/操作),不会产生任何结果(不打印该页面的PDF)...

I have written the code but when I call the controller class by hitting the url (http://localhost:61045/api/Test/Action ) on browser , it does not produce any result(Do not print PDF of that page)...

下面是我的控制器类代码...

Below is my Controller Class code...

命名空间TestWebAPI.Controllers
{
   公共类TestController:ApiController
    {
      公共HttpRequest请求者{ }

namespace TestWebAPI.Controllers
{
    public class TestController : ApiController
    {
        public HttpRequest Requester { get; }

       public HttpResponse Response {get; }

        public HttpResponse Response { get; }

       [HttpGet]
      公共无效Action()
       {
          试试
           {

        [HttpGet]
        public void Action()
        {
            try
            {

               WebClient myClient = new WebClient();
                            字符串myPageHTML = null;
                             StringBuilder strText = new StringBuilder();
                             strText.Append(``< html>< head/>< body>'');
                             byte [] requestHTML;

                WebClient myClient = new WebClient();
                string myPageHTML = null;
                StringBuilder strText = new StringBuilder();
                strText.Append("<html><head/><body>");
                byte[] requestHTML;

               //获取页面的网址
                                   字符串currentPageUrl = Requester.Url.ToString();                              myClient.UseDefaultCredentials = true;
                             UTF8Encoding utf8 =新的UTF8Encoding();

                // Gets the url of the page
                 string currentPageUrl = Requester.Url.ToString();                
                myClient.UseDefaultCredentials = true;
                UTF8Encoding utf8 = new UTF8Encoding();

               requestHTML = myClient.DownloadData(currentPageUrl);

                requestHTML = myClient.DownloadData(currentPageUrl);

               myPageHTML = utf8.GetString(requestHTML);
            
                             HtmlDocument doc =新的HtmlDocument();
                             doc.LoadHtml(myPageHTML);

                myPageHTML = utf8.GetString(requestHTML);
              
                HtmlDocument doc = new HtmlDocument();
                doc.LoadHtml(myPageHTML);

               strText.Append(</body></html>");
                             AddtoPDF(strText.ToString());
           }
           catch(异常例外)
           {
            
           }
       }

                strText.Append("</body></html>");
                AddtoPDF(strText.ToString());
            }
            catch (Exception ex)
            {
              
            }
        }


       ///< summary>
       ///调用此函数以创建html表单.
       ///</summary>
      受保护的void AddtoPDF(string htmlText)
       {
          试试
           {
                             Response.ClearContent();
                             Response.ClearHeaders();
                             Response.ContentType ="application/pdf";
                             Response.AddHeader("content-disposition","attachment; filename = MyPDF.pdf");
                             StringReader sr = new StringReader(htmlText);
                            文档pdfDoc =新文档(PageSize.A4、10f,10f,100f,0f);
                             HTMLWorker htmlparser =新的HTMLWorker(pdfDoc);
                             PdfWriter.GetInstance(pdfDoc,Response.OutputStream);
                             pdfDoc.Open();
                             htmlparser.Parse(sr);
                             pdfDoc.Close();
                             Response.Write(pdfDoc);
                             Response.Flush();
                             Response.Clear();
           }
           catch(异常例外)
           {
            
           }

        /// <summary>
        /// This function is called to create of form html.
        /// </summary>
        protected void AddtoPDF(string htmlText)
        {
            try
            {
                Response.ClearContent();
                Response.ClearHeaders();
                Response.ContentType = "application/pdf";
                Response.AddHeader("content-disposition", "attachment;filename=MyPDF.pdf");
                StringReader sr = new StringReader(htmlText);
                Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 100f, 0f);
                HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
                PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
                pdfDoc.Open();
                htmlparser.Parse(sr);
                pdfDoc.Close();
                Response.Write(pdfDoc);
                Response.Flush();
                Response.Clear();
            }
            catch (Exception ex)
            {
              
            }

       }
  
    }
  
}

        }
  
    }
  
}

推荐答案

我建议您使用JSPDF库满足此要求,您可以在下面的链接中查看示例.

https://gist.github.com/rajendarreddyj/de8bbe0b774c53de1ed5be8dd4ada22b

https://micropyramid.com/blog/export-html-web-page-to-pdf-using-jspdf/

如果您确实想使用网络API,则可以使用pdfsharp库.

https://github.com/empira/PDFsharp/

示例代码:

PdfDocument pdf = new PdfDocument();
            pdf.Info.Title = "My First PDF";
            PdfPage pdfPage = pdf.AddPage();
            XGraphics graph = XGraphics.FromPdfPage(pdfPage);
            XFont font = new XFont("Verdana", 20, XFontStyle.Bold);
            graph.DrawString("This is my first PDF document", font, XBrushes.Black, new XRect(0, 0, pdfPage.Width.Point, pdfPage.Height.Point), XStringFormats.Center);
            string pdfFilename = "firstpage.pdf";            
            using (MemoryStream ms = new MemoryStream())
            {
                pdf.Save(ms, false);
                byte[] buffer = new byte[ms.Length];
                ms.Seek(0, SeekOrigin.Begin);
                ms.Flush();
                ms.Read(buffer, 0, (int)ms.Length);
                byte[] docBytes = ms.ToArray();

                Response.ContentType = "application/pdf";
                Response.AppendHeader("Content-Disposition", "attachment; filename=" + pdfFilename + "");
                Response.Write("<b>File Contents: </b>");
                Response.BinaryWrite(docBytes);

最好的问候,

Lee


这篇关于使用WebAPI控制器打印为PDF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆