将ajax与selectPDF一起使用

时间:2018-06-19 15:25:29

标签: ajax selectpdf

我有以下ajax调用:

$.ajax({
    url: 'WebService.asmx/ConvertPDF',
    data: "{'section':'<html><head></head><body>Ajax html</body></html>'}",
    type: 'POST',
    contentType: 'application/json; charset=utf-8',
    dataType: 'JSON',
    async: false,
    success: function (response) {
        // proceed
    },
    error: function () {
        // fail code
    }
});

和网络服务

[WebMethod(EnableSession = true)]
public void ConvertPDF(string section) {
    HtmlToPdf convertor = new HtmlToPdf();
    string _html = "<html><head></head><body><p>this is a test</p></body></html";

    string size = "A4", orientation = "Portrait";
    PdfPageSize pdfSize = (PdfPageSize)Enum.Parse(typeof(PdfPageSize), size, true);
    PdfPageOrientation pdfOrientation = (PdfPageOrientation)Enum.Parse(typeof(PdfPageOrientation), orientation, true);
    convertor.Options.PdfPageSize = pdfSize;
    convertor.Options.PdfPageOrientation = pdfOrientation;
    convertor.Options.WebPageWidth = 1024;
    convertor.Options.MinPageLoadTime = 2;
    convertor.Options.WebPageHeight = 0;

    PdfDocument doc = convertor.ConvertHtmlString(_html, "");
    doc.Save(HttpContext.Current.Response, false, "Sample.pdf");
    doc.Close();
}

在本地运行service方法可以正常工作,但是当我通过JS按钮调用ajax时,出现“线程正在中止”的情况。

关于如何解决问题的任何想法?基本上,该按钮从页面的各个部分获取html,然后(最终)将其传递给该方法以输出为PDF,基本上用section参数中的_html变量代替了。

谢谢

1 个答案:

答案 0 :(得分:0)

//使用postpdf方法将HTML转换为使用selectpdf

[HttpPost]
    public ActionResult ConvertDocument(MyDocumentDTO model)
    {

        HtmlToPdf converter = new HtmlToPdf();

        PdfDocument doc = converter.ConvertHtmlString(model.Context);
        // save pdf document
        byte[] pdf = doc.Save();

        string handle= Guid.NewGuid().ToString();
        TempData[handle] = pdf;
        return Json(handle, JsonRequestBehavior.AllowGet);

    }

Ajax调用

        $.ajax({
            url: '/document/ConvertDocument',
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            data: ko.toJSON(document),
            success: function (data) {
                window.location = 'download?fileGuid=' + data;
            },

//获取下载文件的请求

    [HttpGet]
    public ActionResult Download(string fileGuid)
    {
        byte[] pdf = TempData[fileGuid] as byte[];
        FileResult fileResult = new FileContentResult(pdf, "application/pdf");
        fileResult.FileDownloadName = "Document.pdf";
        return fileResult;
    }