将生成的PDF文件保存为Azure
问题描述:
我在ASP.NET中有一个表单,在最后一步中填写表单时,它会生成PDF文件.我使用了jsPDF. 我想要的是,生成的pdf文件要在Azure存储中发送(保存),有人可以帮助我吗?
I have a form in ASP.NET and in when I fill up the form in the last step it generates a PDF file. I used jsPDF. What I want is that, the generated pdf file to be send (saved) in Azure storage, does anyone can help me?
谢谢
更新:这是我正在尝试的代码,它可以正常工作,但仅提取文本,不会按原样保存pdf:
UPDATE: This is the code that I'm trying, it's working but it's extracting only the text, it doesn't save the pdf as it is:
var account = new CloudStorageAccount(new Microsoft.WindowsAzure.Storage.Auth.StorageCredentials("storageaccount",
"accesskey"), true);
var blobClient = account.CreateCloudBlobClient();
var container = blobClient.GetContainerReference("folderpath");
StringBuilder text = new StringBuilder();
string filePath = "C:\\Users\\username\\Desktop\\toPDF\\testing PDFs\\test.pdf";
if (File.Exists(filePath))
{
PdfReader pdfReader = new PdfReader(filePath);
for (int page = 1; page <= pdfReader.NumberOfPages; page++)
{
ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();
string currentText = PdfTextExtractor.GetTextFromPage(pdfReader, page, strategy);
currentText = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(currentText)));
text.Append(currentText);
}
pdfReader.Close();
using (MemoryStream ms = new MemoryStream())
{
using (var doc = new iTextSharp.text.Document())
{
PdfWriter writer = PdfWriter.GetInstance(doc, ms);
doc.Open();
doc.Add(new Paragraph(text.ToString()));
}
var byteArray = ms.ToArray();
var blobName = "test.pdf";
var blob = container.GetBlockBlobReference(blobName);
blob.Properties.ContentType = "application/pdf";
blob.UploadFromByteArray(byteArray, 0, byteArray.Length);
}
}
答
我找到了一个简单的解决方案,这就是代码的作用:
I found a simple solution, this is what the code does:
string filePath = "C:\\Users\\username\\Desktop\\toPDF\\testing PDFs\\rpa.pdf";
var credentials = new StorageCredentials("storageaccount","accesskey");
var client = new CloudBlobClient(new Uri("https://jpllanatest.blob.core.windows.net/"), credentials);
// Retrieve a reference to a container. (You need to create one using the mangement portal, or call container.CreateIfNotExists())
var container = client.GetContainerReference("folderpath");
// Retrieve reference to a blob named "myfile.pdf".
var blockBlob = container.GetBlockBlobReference("myfile.pdf");
// Create or overwrite the "myblob" blob with contents from a local file.
using (var fileStream = System.IO.File.OpenRead(filePath))
{
blockBlob.UploadFromStream(fileStream);
}