简体   繁体   English

将Pdf文件保存在特定的文件夹中,而不是下载

[英]save Pdf File in the particular folder instead of downloading

I am doing html to pdf file . 我正在将html转换为pdf文件。 Its Downloading instantly . 立即下载。 I dont want download instantly. 我不想立即下载。 i want to save the file in my project folder once converted. 转换后,我想将文件保存在我的项目文件夹中。

My C# Code 我的C#代码

string html ="<table><tr><td>some contents</td></tr></table>";

        Response.ContentType = "application/pdf";
        Response.AddHeader("content-disposition", "attachment;filename=WelcomeLetter.pdf");

        Response.Cache.SetCacheability(HttpCacheability.NoCache);



        StringWriter sw = new StringWriter();


        HtmlTextWriter hw = new HtmlTextWriter(sw);

        StringReader sr = new StringReader(table);

        Document ResultPDF = new Document(iTextSharp.text.PageSize.A4, 25, 10, 20, 30);         


        PdfPTable Headtable = new PdfPTable(7);
        Headtable.TotalWidth = 525f;
        Headtable.LockedWidth = true;
        Headtable.HeaderRows = 5;
        Headtable.FooterRows = 2;
        Headtable.KeepTogether = true;

        HTMLWorker htmlparser = new HTMLWorker(ResultPDF);
        PdfWriter.GetInstance(ResultPDF, Response.OutputStream);
        ResultPDF.Open();
        htmlparser.Parse(sr);
        ResultPDF.Close();
        Response.Write(ResultPDF);
        Response.End();

For saving pdf file locally in your project folder you can use FileStream class like this. 为了将pdf文件本地保存在您的项目文件夹中,您可以使用FileStream类。

FileStream stream = new FileStream(filePath, FileMode.Create);//Here filePath is path of your project folder.

Now use this stream instead of using Response.OutputStream when you create instance of PdfWriter object. 现在,在创建PdfWriter对象的实例时,请使用此流,而不要使用Response.OutputStream

PdfWriter.GetInstance(ResultPDF, stream);

Now do not use Responce.Write as you don't want to download your file.And close your stream at end. 现在不要使用Responce.Write因为您不想下载文件,并在最后关闭流。

stream.Close();

I'm going to combine everyone's answer into one that you should be able to drop in and use. 我将把每个人的答案组合成一个您应该可以使用的答案。 If this works, I would accept Manish Parakhiya's answer because that had the most important part. 如果这有效,我将接受Manish Parakhiya的回答,因为那是最重要的部分。

First, I'm going to assume you are using a recent version of iTextSharp. 首先,我假设您使用的是iTextSharp的最新版本。 I think 5.5.5 is the most recent version. 我认为5.5.5是最新版本。 Second, because of this, I'm going to restructure your code a bit in order to use the using pattern. 其次,由于这个原因,我将对您的代码进行一些重组,以使用using模式。 If you're stuck on an older obsolete unsupported version like 4.1.6 you'll need to re-adjust. 如果您使用的是过时的不支持的旧版本(例如4.1.6),则需要重新调整。

Almost every tutorial out there shows you that you can bind directly the Response.OutputStream . 几乎所有的教程都向您表明,您可以直接绑定Response.OutputStream This is 100% valid but I would argue that it is also a really bad idea. 这是100%有效的,但我认为这也是一个非常糟糕的主意。 Instead, bind to a more generic MemoryStream . 而是绑定到更通用的MemoryStream This makes debugging much easier and your code will port and adapt that much easier. 这使调试变得更加容易,并且您的代码将更容易移植和修改。

The below code includes comments about each of the changes and what things are actually doing. 以下代码包含有关每个更改以及实际操作的注释。 The top section is all about creating a PDF from a string of HTML. 最上面的部分是关于用HTML字符串创建PDF。 The bottom actually does something with it, including writing it to disk and/or streaming it to a browser. 底部实际上对其进行了某些操作,包括将其写入磁盘和/或将其流式传输到浏览器。

//Will hold our PDF eventually
Byte[] bytes;

//HTML that we want to parse
string html = "<table><tr><td>some contents</td></tr></table>";

//Create a MemoryStream to write our PDF to
using (var ms = new MemoryStream()) {

    //Create our document abstraction
    using (var ResultPDF = new Document(iTextSharp.text.PageSize.A4, 25, 10, 20, 30)) {

        //Bind a writer to our Document abstraction and our stream
        using (var writer = PdfWriter.GetInstance(ResultPDF, ms)) {

            //Open the PDF for writing
            ResultPDF.Open();

            //Parse our HTML using the old, obsolete, not support parser
            using (var sw = new StringWriter()) {
                using (var hw = new HtmlTextWriter(sw)) {
                    using (var sr = new StringReader(html)) {
                        using (var htmlparser = new HTMLWorker(ResultPDF)) {
                            htmlparser.Parse(sr);
                        }
                    }
                }
            }

            //Close the PDF
            ResultPDF.Close();
        }
    }

    //Grab the raw bytes of the PDF
    bytes = ms.ToArray();
}

//At this point, the bytes variable holds a valid PDF file.
//You can write it disk:
System.IO.File.WriteAllBytes("your file path here", bytes);

//You can also send it to a browser:
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=WelcomeLetter.pdf");
Response.BinaryWrite(bytes);
Response.Cache.SetCacheability(HttpCacheability.NoCache);

//Never do the next line, it doesn't do what you think it does and actually produces corrupt PDFs
//Response.Write(ResultPDF); //BAD!!!!!!
Response.End();
string tempDirectory = Session.SessionID.ToString();
string location = Path.Combine(Server.MapPath(
    WebConfigurationManager.AppSettings["PathSet"].ToString()), tempDirectory);
if (!Directory.Exists(location))
{
    Directory.CreateDirectory(location);
}
string fileName="abc.pdf";
filePath = Path.Combine(location, fileName);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM