Encrypt PDF file that contains an image only - c#

I am using iTextSharp to convert image files(.jpg, .png etc.) to PDF files. Now, there is a requirement to encrypt these PDF files without any password protection. I have tried the writer.SetEncryption method to encrypt the files, but when I open the PDFs from where they are saved in the directory, I can see their contents. Apparently, no encryption took place. . How can I get these PDFs encrypted?
public JsonResult ImagetoPDFOpenInDiv(HttpPostedFileBase file)
{
string filename = file.First().FileName;
string targetpath = Server.MapPath("~/Doc/");
string filepath = targetpath + filename + ".pdf";
using (MemoryStream stream = new System.IO.MemoryStream())
{
//Initialize the PDF document object.
using (Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 10f))
{
PdfWriter writer = PdfWriter.GetInstance(pdfDoc, new FileStream(filepath, FileMode.Create));
writer.SetEncryption(null,null,PdfWriter.AllowPrinting, PdfWriter.ENCRYPTION_AES_256);
pdfDoc.Open();
//Add the Image file to the PDF document object.
iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(file.InputStream);
if (img.Width >= 585 || img.Height >= 830)
{
var scalePercent = (((pdfDoc.PageSize.Width / img.Width) * 100) - 4);
img.ScalePercent(scalePercent);
}
pdfDoc.Add(img);
pdfDoc.Close();
// Returning the virtual path of the pdf file generated.. in message.
return Json(new { success = true, message = "/Doc/"+ trimFileName + ".pdf" });
}
}
}

Related

c# save pdf file to specific path

I am using Visual Studio 2012. I am converting an aspx page into a PDF file.
It works fine...
the code is like this
string attachment = "attachment; filename=" + FileName + ".pdf";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/pdf";
StringWriter s_tw = new StringWriter();
HtmlTextWriter h_textw = new HtmlTextWriter(s_tw);
h_textw.AddStyleAttribute("font-size", "7pt");
h_textw.AddStyleAttribute("color", "Black");
pnlPrincipal.RenderControl(h_textw);//Name of the Panel
Document doc = new Document();
doc = new Document(PageSize.A4, 5, 5, 15, 5);
FontFactory.GetFont("Verdana", 80, iTextSharp.text.BaseColor.RED);
PdfWriter.GetInstance(doc, Response.OutputStream);
doc.Open();
StringReader s_tr = new StringReader(s_tw.ToString());
HTMLWorker html_worker = new HTMLWorker(doc);
html_worker.Parse(s_tr);
doc.Close();
Response.Write( doc);
The problem I am facing is that it is saved in c:/Users/Download folder.
I want to save the file in an specific folder.
Where can I specified that?
Thanks
You can write a document with
string folder = #"C:\Temp\";
string fileName = "mydocument.txt";
string fullPath = folder + fileName;
string data = "My string to write in a document";
File.WriteAllLines(fullPath, data);
// Read & print in console
string readText = File.ReadAllText(fullPath);
Console.WriteLine(readText);
Finally I found the way...
Instead of using Response I have to use FileStream
System.IO.FileStream fs = new FileStream(Server.MapPath("PDFDIR") + "\\" + otd.NumeroOTD.ToString() + ".pdf", FileMode.Create);
StringWriter s_tw = new StringWriter();
HtmlTextWriter h_textw = new HtmlTextWriter(s_tw);
h_textw.AddStyleAttribute("font-size", "7pt");
h_textw.AddStyleAttribute("color", "Black");
pnlPrincipal.RenderControl(h_textw);//Name of the Panel
// Create an instance of the document class which represents the PDF document itself.
Document document = new Document(PageSize.A4, 25, 25, 30, 30);
// Create an instance to the PDF file by creating an instance of the PDF
// Writer class using the document and the filestrem in the constructor.
FontFactory.GetFont("Verdana", 80, iTextSharp.text.BaseColor.RED);
PdfWriter writer = PdfWriter.GetInstance(document, fs);
document.AddCreator("Sample application using iTextSharp");
document.AddSubject("Document subject - Describing the steps creating a PDF document");
document.AddTitle("The document title - PDF creation using iTextSharp");
// Open the document to enable you to write to the document
document.Open();
// Add a simple and wellknown phrase to the document in a flow layout manner
// document.Add(new Paragraph("Hello World!"));
StringReader s_tr = new StringReader(s_tw.ToString());
HTMLWorker html_worker = new HTMLWorker(document);
html_worker.Parse(s_tr);
// Close the document
document.Close();
// Close the writer instance
writer.Close();
// Always close open filehandles explicity
fs.Close();

iTextSharp (version 4.1.6) - add text/table at top of existing PDF

I have a pdf document (created by iTextSharp - free version 4.1.6) and I want to add text / table at the top of this pdf. I have tried to create two memory streams from iTextSharp Documents and combine them to one, see my code below. But the new PDF file cannot be opened. Any ideas what I am doing wrong? Any other ideas to add text / table at the top of an existing PDF? Thanks in advance!
public void CreateTestPDF(string _pathOfOriginalPDF, string _pathOfModifiedPDF)
{
string oldFile = _pathOfOriginalPDF;
string newFile = pathOfModifiedPDF;
byte[] bytesHeader;
byte[] bytesBody;
byte[] bytesCombined;
using (MemoryStream ms = new MemoryStream())
{
Document doc = new Document();
doc.Open();
doc.Add(new Paragraph("This is my header paragraph"));
if (doc.IsOpen())
{
doc.Close();
}
bytesHeader = ms.ToArray();
}
using (MemoryStream ms = new MemoryStream())
{
Document doc = new Document();
//doc.Open();
PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(oldFile, FileMode.Create));
if (doc.IsOpen())
{
doc.Close();
}
bytesBody = ms.ToArray();
}
IEnumerable<byte> iCombined = bytesHeader.Concat(bytesBody);
bytesCombined = iCombined.ToArray();
string testFile = _pathOfModifiedPDF;
using (FileStream fs = File.Create(testFile))
{
fs.Write(bytesBody, 0, (int)bytesBody.Length);
}
}

How can save pdf genrated file to project folder using asp.net C#?

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));

how to save pdf file in folder without save dialog c# windows application

This is my code for opening a PDF file. I need this file to be saved to a certain location in my computer eg.: #"c:\temp\"
List<string> pdfFiles = new List<string>();
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.CheckFileExists = true;
openFileDialog.AddExtension = true;
openFileDialog.Multiselect = true;
openFileDialog.Filter = "PDF files (*.pdf)|*.pdf";
if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
pdfFiles = new List<string>();
foreach (string fileName in openFileDialog.FileNames)
pdfFiles.Add(fileName);
}
You can use the File.Copy method to copy the file to its new location.
First, obtain the path of the file in the old location and desired new location.
Then, apply this method.
File.Copy(#"C:\old.txt", #"C:\new.txt");
try this
add this Reference file - iTextSharp.text.pdf
string Folderpath ="your path";
using (FileStream stream = new FileStream(Folderpath, FileMode.Create))
{
Document pdfDoc = new Document(PageSize.A2, 10f, 10f, 10f, 0f);
PdfWriter.GetInstance(pdfDoc, stream);
pdfDoc.Open();
// Paragraph k = new Paragraph("Your PDF ");
// pdfDoc.Add(k);
pdfDoc.Close();
stream.Close();
}

Writing MemoryStream into SaveAs Dialogue Box in WInform

I have an image which i want to write into itext Pdf file using c#.Here is my code to generate image from chart and write into itext pdf file.
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
using (MemoryStream stream = new MemoryStream())
{
pdfDoc.Open();
pieChart.SaveImage(stream, ChartImageFormat.Png);
iTextSharp.text.Image chartImage = iTextSharp.text.Image.GetInstance(stream.GetBuffer());
chartImage.ScalePercent(75f);
pdfDoc.Add(chartImage);
}
pdfDoc.Close();
Now as per my reuirement i have to open this pdf file using Save as dialogue box.Here is the code by which i an trying to open this pdf file..
Stream myStream;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "Pdf files (*.pdf)|*.pdf|All files (*.*)|*.*";
saveFileDialog1.FilterIndex = 0;
saveFileDialog1.RestoreDirectory = true;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if ((myStream = saveFileDialog1.OpenFile()) != null)
{
// Code to write the stream goes here.
PdfWriter.GetInstance(pdfDoc, myStream);
myStream.Close();
}
}
But i am not able to get the pdf file.Dialogue Box is coming but i am not able to get the pdf file.
Please help me to resolve the issue .
Thanks in advance.
you need to save ur streambytes data to a file ...
Stream myStream;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "Pdf files (*.pdf)|*.pdf|All files (*.*)|*.*";
saveFileDialog1.FilterIndex = 0;
saveFileDialog1.RestoreDirectory = true;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if ((myStream = saveFileDialog1.OpenFile()) != null)
{
// Code to write the stream goes here.
PdfWriter.GetInstance(pdfDoc, myStream);
myStream.Close();
using (FileStream file = new FileStream(saveFileDialog1.FileName, FileMode.Create, System.IO.FileAccess.Write,FileShare.ReadWrite)) {
byte[] bytes = new byte[myStream.Length];
ms.Read(bytes, 0, (int)myStream.Length);
file.Write(bytes, 0, bytes.Length);
myStream.Close();
}
}
}
you can write stream data using streamwriter...

Categories

Resources