I'm trying to open a PDF with itextsharp that was encrypted with AES 256 and display it. The PDF was encrypted with itextsharp as well. I'm using iTextSharp 5.5.0.0. This code works if the encryption is set to 'standard encryption'.
An exception is thrown on the closing bracket of the inner 'using': Arithmetic operation resulted in an overflow.
string path = Server.MapPath("~/App_Data/pdf/foo.pdf");
string password = "openSesame";
Response.Clear();
Response.ClearHeaders();
Response.AddHeader("Expires", "0");
Response.AddHeader("Cache-Control", "private");
Response.AddHeader("content-disposition", "inline");
Response.ContentType = "application/pdf";
using (MemoryStream memoryStream = new MemoryStream())
{
using (PdfReader reader = new PdfReader(path, Encoding.UTF8.GetBytes(password)))
using (PdfStamper stamper = new PdfStamper(reader, memoryStream))
{
}
Response.BinaryWrite(memoryStream.GetBuffer());
}
Response.End();
Update (forgot encryption code):
using (FileStream fileStream = new FileStream(path, FileMode.Create))
{
PdfCopyFields copy = new PdfCopyFields(fileStream);
var bytes = Encoding.UTF8.GetBytes(password);
copy.SetEncryption(bytes, bytes, 0, PdfWriter.ENCRYPTION_AES_256);
// add some documents with 'copy.AddDocument()';
copy.Close();
}
Am I missing something?
Here's a quick sample I put together that works to encrypt a PDF with 256-bit AES encryption:
var openDialog = new OpenFileDialog();
openDialog.DefaultExt = "pdf";
if (openDialog.ShowDialog() == true)
{
using (var input = openDialog.OpenFile())
{
var saveDialog = new SaveFileDialog();
saveDialog.DefaultExt = "pdf";
if (saveDialog.ShowDialog() == true)
{
using (var reader = new PdfReader(input))
{
using (var output = saveDialog.OpenFile())
{
PdfEncryptor.Encrypt(
reader, output,
PdfWriter.ENCRYPTION_AES_256,
"password", "password",
PdfWriter.ALLOW_PRINTING);
}
}
}
}
}
Related
I am trying to create a ZipArchive in memory and append several entries with binary data from database. The problem is that after loop, zip sent to client is invalid/empty. Can you please check my code?
using (MemoryStream _memory_stream = new MemoryStream())
{
using (ZipArchive _archive = new ZipArchive(_memory_stream, ZipArchiveMode.Create, true))
{
foreach (byte[] binaryData in this.FileBinaries)
{
ZipArchiveEntry _entry = _archive.CreateEntry(str_filename, CompressionLevel.Optimal);
using (Stream _entryStream = _entry.Open())
{
using (StreamWriter _writer = new StreamWriter(_entryStream))
{
_writer.Write(binaryData);
}
_entryStream.Close();
}
}
}
Response.AppendHeader("content-disposition", "attachment; filename=certificates.zip");
Response.ContentType = "application/zip";
Response.Write(_memory_stream);
}
Using c# and iText7 I need to modify an existing PDF and save it to blob storage.
I have a console app that does exactly what I need using the file system:
PdfReader reader = new PdfReader(source);
PdfWriter writer = new PdfWriter(destination2);
PdfDocument pdfDoc = new PdfDocument(reader, writer);
PdfAcroForm form = PdfAcroForm.GetAcroForm(pdfDoc, true);
fields = form.GetFormFields();
fields.TryGetValue("header", out PdfFormField cl);
var type = cl.GetType();
cl.SetValue("This is a header");
pdfDoc.Close();
This works just fine. However I can not figure out how to do the same thing pulling the PDF from blob storage and sending the new one to blob storage
IDictionary<string, PdfFormField> fields;
MemoryStream outStream = new MemoryStream();
var pdfTemplate = _blobStorageService.GetBlob("mycontainer", "TestPDF.pdf");
PdfReader reader = new PdfReader(pdfTemplate);
PdfWriter writer = new PdfWriter(outStream);
PdfDocument pdfDoc = new PdfDocument(reader, writer);
PdfAcroForm form = PdfAcroForm.GetAcroForm(pdfDoc, true);
fields = form.GetFormFields();
fields.TryGetValue("header", out PdfFormField cl);
cl.SetValue("This is a header");
pdfDoc.Close();
outStream.Position = 0;
_blobStorageService.UploadBlobAsync("mycontainer", **THIS IS THE ISSUE**, "newpdf.pdf");
I think I need to get pdfDoc as a byte array. Outstream is incorrect, it is only has a length of 15
The code below shows how to read a PDF from a file into a byte[] and also how to modify a PDF that's stored as a byte[].
Download and install NuGet package: iText7
In Solution Explorer, right-click <project name> and select Manage NuGet Packages...
Click Browse
In the search box type: iText7
Select iText7
Select desired version
Click Install
Add the following using statements:
using System.IO;
using iText.Kernel.Pdf;
using iText.Forms;
using iText.Forms.Fields;
Get PDF as byte[] (GetPdfBytes):
public static Task<byte[]> GetPdfBytes(string pdfFilename)
{
byte[] pdfBytes = null;
using (PdfReader reader = new PdfReader(pdfFilename))
{
using (MemoryStream msPdfWriter = new MemoryStream())
{
using (PdfWriter writer = new PdfWriter(msPdfWriter))
{
using (PdfDocument pdfDoc = new PdfDocument(reader, writer))
{
//don't close underlying streams when PdfDocument is closed
pdfDoc.SetCloseReader(false);
pdfDoc.SetCloseWriter(false);
//close
pdfDoc.Close();
//set value
msPdfWriter.Position = 0;
//convert to byte[]
pdfBytes = msPdfWriter.ToArray();
}
}
}
}
return Task.FromResult(pdfBytes);
}
Usage:
byte[] pdfBytes = null;
string filename = string.Empty;
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "PDF File (*.pdf)|*.pdf";
if (ofd.ShowDialog() == DialogResult.OK)
{
//get PDF as byte[]
var tResult = GetPdfBytes(ofd.FileName);
pdfBytes = tResult.Result;
//For testing, write back to file so we can ensure that the PDF file opens properly
//create a new filename
filename = System.IO.Path.GetFileNameWithoutExtension(ofd.FileName) + " - Test.pdf";
filename = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(ofd.FileName), filename);
//save to file
File.WriteAllBytes(filename, pdfBytes);
System.Diagnostics.Debug.WriteLine("Saved as '" + filename + "'");
}
Modify PDF that's stored in a byte[] (ModifyPdf)
public static Task<byte[]> ModifyPdf(byte[] pdfBytes)
{
byte[] modifiedPdfBytes = null;
using (MemoryStream ms = new MemoryStream(pdfBytes))
{
using (PdfReader reader = new PdfReader(ms))
{
using (MemoryStream msPdfWriter = new MemoryStream())
{
using (PdfWriter writer = new PdfWriter(msPdfWriter))
{
using (PdfDocument pdfDoc = new PdfDocument(reader, writer))
{
//don't close underlying streams when PdfDocument is closed
pdfDoc.SetCloseReader(false);
pdfDoc.SetCloseWriter(false);
//get AcroForm from document
PdfAcroForm form = PdfAcroForm.GetAcroForm(pdfDoc, true);
//get form fields
IDictionary<string, PdfFormField> fields = form.GetFormFields();
//for testing, show all fields
foreach (KeyValuePair<string, PdfFormField> kvp in fields)
{
System.Diagnostics.Debug.WriteLine("Key: '" + kvp.Key + "' Value: '" + kvp.Value + "'");
}
PdfFormField cl = null;
//get specified field
fields.TryGetValue("1 Employee name", out cl);
//set value for specified field
cl.SetValue("John Doe");
//close PdfDocument
pdfDoc.Close();
//set value
msPdfWriter.Position = 0;
//convert to byte[]
modifiedPdfBytes = msPdfWriter.ToArray();
}
}
}
}
}
return Task.FromResult(modifiedPdfBytes);
}
Usage:
byte[] pdfBytes = null;
string filename = string.Empty;
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "PDF File (*.pdf)|*.pdf";
if (ofd.ShowDialog() == DialogResult.OK)
{
//get PDF as byte[]
var tResult = GetPdfBytes(ofd.FileName);
pdfBytes = tResult.Result;
//modify PDF
pdfBytes = await ModifyPdf(pdfBytes);
//create a new filename
filename = System.IO.Path.GetFileNameWithoutExtension(ofd.FileName) + " - TestModified.pdf";
filename = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(ofd.FileName), filename);
//save to file
File.WriteAllBytes(filename, pdfBytes);
System.Diagnostics.Debug.WriteLine("Saved as '" + filename + "'");
}
The code below is adapted from Sample01b_HelloWorldAsync.cs and is untested.
Download and install NuGet package: Azure.Storage.Blobs
Add the following using statement:
using Azure.Storage.Blobs;
DownloadPdf:
public static async Task<byte[]> DownloadPdf(string connectionString, string blobContainerName, string blobName)
{
byte[] pdfBytes = null;
using (MemoryStream ms = new MemoryStream())
{
// Get a reference to the container and then create it
BlobContainerClient container = new BlobContainerClient(connectionString, blobContainerName);
Azure.Response<Azure.Storage.Blobs.Models.BlobContainerInfo> responseCA = await container.CreateAsync();
// Get a reference to the blob
BlobClient blob = container.GetBlobClient(blobName);
// Download the blob's contents and save it to a file
Azure.Response responseDTA = await blob.DownloadToAsync(ms);
//set value
ms.Position = 0;
//convert to byte[]
pdfBytes = ms.ToArray();
}
return pdfBytes;
}
UploadPdf:
public static async Task<Azure.Response<Azure.Storage.Blobs.Models.BlobContentInfo>> UpdloadPdf(byte[] pdfBytes, string connectionString, string blobContainerName, string blobName)
{
Azure.Response<Azure.Storage.Blobs.Models.BlobContentInfo> result = null;
using (MemoryStream ms = new MemoryStream(pdfBytes))
{
//this statement may not be necessary
ms.Position = 0;
// Get a reference to the container and then create it
BlobContainerClient container = new BlobContainerClient(connectionString, blobContainerName);
await container.CreateAsync();
// Get a reference to the blob
BlobClient blob = container.GetBlobClient(blobName);
//upload
result = await blob.UploadAsync(ms);
}
return result;
}
Here's a PDF file for testing.
I have generated a pdf file from html and now I need to save it to a folder in my project.
I am able to get the generated pdf to download locally but when I send it to the file folder it gets corrupted and will not open.
public void CreateHTML(ComplaintIntakeData cd)
{
string formHtml = "<table class=\"MsoNormal\">";
string complaintTypeHtml = PCSUtilities.GetComplaintTypeHTML(cd);
string providerHtml = "";
if (cd.Providers != null && cd.Providers.Count > 0)
{
providerHtml = PCSUtilities.GetProviderHTML(cd);
}
string facilityHtml = PCSUtilities.GetFacilityHTML(cd);
string anonymousHtml = PCSUtilities.GetAnonymousHTML(cd);
string contactHtml = PCSUtilities.GetContactHTML(cd);
string patientHtml = PCSUtilities.GetPatientHTML(cd);
string detailsHtml = PCSUtilities.GetComplaintDetailsHTML(cd);
formHtml = formHtml + complaintTypeHtml + providerHtml + facilityHtml + anonymousHtml + contactHtml + patientHtml + detailsHtml + "</table>";
formHtml = formHtml.Replace("''", "\"");
// Load HTML template for letter and replace template fields with provider data
string htmlContent = File.ReadAllText(Server.MapPath("~/ComplaintIntakeForm.html"));
htmlContent = htmlContent.Replace("<%ComplaintInformation%>", formHtml);
string fileName = "ComplaintIntakeFile_" + cd.ComplaintGuid.ToString() +".pdf";
using (MemoryStream memStream = new MemoryStream())
{
try
{
// Load up a new PDF doc.
iTextSharp.text.Document pdfDoc = new iTextSharp.text.Document(PageSize.LETTER);
PdfWriter writer = PdfWriter.GetInstance(pdfDoc, memStream);
// writer.CompressionLevel = PdfStream.NO_COMPRESSION;
// Make document tagged PDFVERSION_1_7
writer.SetPdfVersion(PdfWriter.PDF_VERSION_1_7);
writer.SetTagged();
// Set document metadata
writer.ViewerPreferences = PdfWriter.DisplayDocTitle;
pdfDoc.AddLanguage("en-US");
pdfDoc.AddTitle("Complaint Intake Form");
writer.CreateXmpMetadata();
pdfDoc.Open();
var tagProcessors = (DefaultTagProcessorFactory)Tags.GetHtmlTagProcessorFactory();
//tagProcessors.RemoveProcessor(HTML.Tag.IMG);
//tagProcessors.AddProcessor(HTML.Tag.IMG, new CustomImageTagProcessor());
var cssFiles = new CssFilesImpl();
cssFiles.Add(XMLWorkerHelper.GetInstance().GetDefaultCSS());
var cssResolver = new StyleAttrCSSResolver(cssFiles);
var charset = Encoding.UTF8;
var context = new HtmlPipelineContext(new CssAppliersImpl(new XMLWorkerFontProvider()));
context.SetAcceptUnknown(true).AutoBookmark(true).SetTagFactory(tagProcessors);
var htmlPipeline = new HtmlPipeline(context, new PdfWriterPipeline(pdfDoc, writer));
var cssPipeline = new CssResolverPipeline(cssResolver, htmlPipeline);
var worker = new XMLWorker(cssPipeline, true);
var xmlParser = new XMLParser(true, worker, charset);
try
{
using (var sr = new StringReader(htmlContent))
{
xmlParser.Parse(sr);
// xmlParser.Flush();
}
}
catch (Exception e)
{
Response.Write(e.Message);
}
pdfDoc.Close();
//writer.Close();
///this creates a pdf download.
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
Response.OutputStream.Write(memStream.GetBuffer(), 0, memStream.GetBuffer().Length);
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show("The following error occurred:\n" + ex.ToString());
}
}
}
when I add the following to create the file. The file is created but it is corrupted and cannot open as a pdf
using (FileStream file = new FileStream(Server.MapPath("~/tempFiles/") + fileName, FileMode.CreateNew))
{
byte[] bytes = new byte[memStream.Length];
memStream.Read(bytes, 0, memStream.Length);
file.Write(bytes, 0, bytes.Length);
}
I think this answer is relevant:
Copy MemoryStream to FileStream and save the file?
Your two code snippets use both memStream and memString and without seeing all the code in context, I'm guessing. Assuming memStream is a Stream that contains the contents of your PDF, you can write it to a file like this:
using (FileStream file = new FileStream(Server.MapPath("~/tempFiles/") + fileName, FileMode.CreateNew))
{
memStream.Position = 0;
memStream.CopyTo(file);
}
I wound up moving the new FileStream call into the PdfWriter.GetInstance method in place of the memStream variable. And was able to get rid of the using filestream code all together.
PdfWriter writer = PdfWriter.GetInstance(pdfDoc, new FileStream(Server.MapPath(path)+"/" + fileName, FileMode.CreateNew));
I'm generating a pdf using itextsharp. I then want to upload that file directly to amazon S3.
Previously when I was uploading a file I could use this and get the input stream of that file. Like so:
AmazonS3Config S3Config = new AmazonS3Config
{
RegionEndpoint = RegionEndpoint.USEast1, //its default region set by amazon
};
AmazonS3Client client;
using (client = new Amazon.S3.AmazonS3Client(_awsAccessKey, _awsSecretKey, S3Config))
{
var request = new PutObjectRequest()
{
BucketName = _bucketName,
CannedACL = S3CannedACL.PublicRead,
Key = string.Format("UPLOADS/{0}", file.FileName),
InputStream = file.InputStream
};
client.PutObject(request);
}
I haven't been able to find a way to get an input stream from my generated pdf I did read I could recreate the file and read it back, but I could't get that to work.
Edit: Adding code used to generate pdf
using (var ms = new System.IO.MemoryStream())
{
var document = new Document(PageSize.A4, 20f, 10f, 30f, 0f);
{
PdfWriter writer = PdfWriter.GetInstance(document, ms);
document.Open();
try
{
Paragraph header = new Paragraph("Test Document");
document.Add(header);
}
catch (Exception ex)
{
Console.WriteLine("{0} Exception caught.", ex);
}
finally
{
document.Close();
byte[] bytes = ms.ToArray();
ms.Close();
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment; filename=Contract for cancellation of " + order.OrderID + ".pdf");
Response.ContentType = "application/pdf";
Response.Buffer = true;
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BinaryWrite(bytes);
Response.End();
}
Would really appreciate any help on this
I have generated a pdf file with password protection by using the following code:
using (Stream input = new FileStream(InputFile, FileMode.Open, FileAccess.Read, FileShare.Read))
{
using (Stream output = new FileStream(OutputFile, FileMode.Create, FileAccess.Write, FileShare.None))
{
PdfReader reader = new PdfReader(input);
PdfEncryptor.Encrypt(reader, output, true, strDob, "secret", PdfWriter.ALLOW_SCREENREADERS);
}
}
I want to remove the password for the PDF file generated using the above code based on my certain condtions through code.
string WorkingFolder = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string InputFile = Path.Combine(WorkingFolder, "test.pdf");
string OutputFile = Path.Combine(WorkingFolder, "test_dec.pdf");//will be created automatically
//You must provide owner password but not the user password .
private void DecryptFile(string inputFile, string outputFile)
{
string password = #"secret"; // Your Key Here
try
{
PdfReader reader = new PdfReader(inputFile, new System.Text.ASCIIEncoding().GetBytes(password));
using (MemoryStream memoryStream = new MemoryStream())
{
PdfStamper stamper = new PdfStamper(reader, memoryStream);
stamper.Close();
reader.Close();
File.WriteAllBytes(outputFile, memoryStream.ToArray());
}
}
catch (Exception err)
{
Console.WriteLine(err.Message);
}
}