0
想只是一個文本添加到使用itextsharp 。而到目前爲止,我done.my代碼現有的PDF =>無法訪問已關閉的文件.net MVC?
public FileStreamResult DownloadCertificate(string UserId)
{
//get user info using UserId from database
//UserDetail UserDetail = db.UserDetails.Where(x => x.UserId == UserId).FirstOrDefault();
string oldFile = Server.MapPath("~/Content/img/tsms/Certificate/Certificate-of-Completion-Award-Template-Blue.pdf");
string newFile = Server.MapPath("~/Content/img/tsms/Certificate/newFile.pdf");
// open the reader
PdfReader reader = new PdfReader(oldFile);
Rectangle size = reader.GetPageSizeWithRotation(1);
Document document = new Document(size);
// open the writer
FileStream fs = new FileStream(newFile, FileMode.Create, FileAccess.Write);
PdfWriter writer = PdfWriter.GetInstance(document, fs);
document.Open();
// the pdf content
PdfContentByte cb = writer.DirectContent;
// select the font properties
BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
cb.SetColorFill(BaseColor.DARK_GRAY);
cb.SetFontAndSize(bf, 8);
// write the text in the pdf content
cb.BeginText();
string text = "Some random blablablabla...";
// put the alignment and coordinates here
cb.ShowTextAligned(1, text, 520, 640, 0);
cb.EndText();
// write the text in the pdf content
cb.BeginText();
text = "Other random blabla...";
// put the alignment and coordinates here
cb.ShowTextAligned(2, text, 100, 200, 0);
cb.EndText();
// create the new page and add it to the pdf
PdfImportedPage page = writer.GetImportedPage(reader, 1);
cb.AddTemplate(page, 0, 0);
// close the streams and voilá the file should be changed :)
document.Close();
fs.Close();
writer.Close();
reader.Close();
return new FileStreamResult(fs, "application/pdf");
}
我不知道爲什麼它給了我這種錯誤。
我試圖找到解決方案。我發現.... FileStream "cannot access closed file"
但這對我來說還不夠。
我也嘗試改變我的代碼中的一些行。下面=>
// close the streams and voilá the file should be changed :)
document.Close();
//fs.Close();
//writer.Close();
//reader.Close();
return new FileStreamResult(fs, "application/pdf");
但這種改變也沒有幫助我。在我的代碼中我做了什麼錯誤(也是如何爲用戶提供下載模式)。
你有兩個問題。您已將您的問題的第一部分用您更改的塊「下面的=>」回答 - 您在關閉「fs.close」後嘗試訪問「fs」。你想保存你的FileStreamResult到一個局部變量,然後關閉你的文檔,文件流等等,最後返回本地的FileStreamResult變量。你的錯誤信息已經給你答案。重讀它,並查看您的變量名稱以及您關閉它們並訪問它們以尋找線索的位置。 GL – mjw
@mjw你是對的。現在更改'//document.Close(); //fs.Close(); //writer.Close(); //reader.Close();'但之後,它顯示我anothre錯誤[鏈接](https://postimg.org/image/vp3wesgb1/)你可以說任何關於... –
改變你的FileStream構造函數調用to:FileStream fs = new FileStream(newFile,FileMode.Create,FileAccess.ReadWrite); – mjw