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...
Related
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" });
}
}
}
I am trying to create a desktop application combining existing pdf files into one.
I found some code that helps me with my design and selecting the files and merging them but my code creates pdf files and then sends the new file to the desktop. I need my code to grab existing pdf files and merging them together to create a file with those files together and have it sent to my desktop. Attached is my code, please let me know what I need to fix. I am very new to C# I understand basics but I am unsure where to change things and how to in this certain area.
namespace mergePdf
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnMerge_Click(object sender, EventArgs e)
{
//Folder that we'll work from
string workingFolder =
Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string pdf1 = Path.Combine(workingFolder, "pdf1.pdf");//PDF
with solid red background color
string pdf2 = Path.Combine(workingFolder, "pdf2.pdf");//PDF
with text
string pdf3 = Path.Combine(workingFolder, "pdf3.pdf");
//Merged PDF
//Create a basic PDF filled with red, nothing special
using (FileStream fs = new FileStream(pdf1, FileMode.Create,
FileAccess.Write, FileShare.None))
{
using (Document doc = new Document(PageSize.LETTER))
{
using (PdfWriter writer = PdfWriter.GetInstance(doc,
fs))
{
doc.Open();
PdfContentByte cb = writer.DirectContent;
cb.SetColorFill(BaseColor.RED);
cb.Rectangle(0, 0, doc.PageSize.Width,
doc.PageSize.Height);
cb.Fill();
doc.Close();
}
}
}
//Create a basic PDF with a single line of text, nothing
special
using (FileStream fs = new FileStream(pdf2, FileMode.Create,
FileAccess.Write, FileShare.None))
{
using (Document doc = new Document(PageSize.LETTER))
{
using (PdfWriter writer = PdfWriter.GetInstance(doc,
fs))
{
doc.Open();
doc.Add(new Paragraph("This is a test"));
doc.Close();
}
}
}
//Create a basic PDF
using (FileStream fs = new FileStream(pdf3, FileMode.Create,
FileAccess.Write, FileShare.None))
{
using (Document doc = new Document(PageSize.LETTER))
{
using (PdfWriter writer = PdfWriter.GetInstance(doc,
fs))
{
doc.Open();
//Get page 1 of the first file
PdfImportedPage imp1 = writer.GetImportedPage(new
PdfReader(pdf1), 1);
//Get page 2 of the second file
PdfImportedPage imp2 = writer.GetImportedPage(new
PdfReader(pdf2), 1);
//Add the first file to coordinates 0,0
writer.DirectContent.AddTemplate(imp1, 0, 0);
//Since we don't call NewPage the next call will
operate on the same page
writer.DirectContent.AddTemplate(imp2, 0, 0);
doc.Close();
}
}
}
this.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
textBoxPdfFile1Path.Text =
System.IO.Path.Combine(Application.StartupPath,
#"C:\Users\jesse\Downloads");
textBoxPdfFile2Path.Text =
System.IO.Path.Combine(Application.StartupPath,
#"C:\Users\jesse\Downloads");
}
private void btnSelectFile1_Click(object sender, EventArgs e)
{
OpenFileDialog fd = new OpenFileDialog();
fd.Filter = "PDF files (*.pdf)|*.pdf|All files (*.*)|*.*";
if (fd.ShowDialog() == DialogResult.OK)
{
textBoxPdfFile1Path.Text = fd.FileName;
}
}
private void btnSelectFile2_Click(object sender, EventArgs e)
{
OpenFileDialog fd = new OpenFileDialog();
fd.Filter = "PDF files (*.pdf)|*.pdf|All files (*.*)|*.*";
if (fd.ShowDialog() == DialogResult.OK)
{
textBoxPdfFile2Path.Text = fd.FileName;
}
}
}
}
I expect the output to combine existing files into one file which will be sent to my desktop. Right now it creates two pdf sample files and combines them but I have no idea how to select from existing instead.
Using the below code should do what you want as far merging the documents.
To get a list of the actual paths to the individual pdfs is up to you on how to do.
Once the FileStream is closed your document should be created at the specified 'newPdfPath' path.
using (FileStream stream = new FileStream(newPdfPath, FileMode.Create))
{
Document document = new Document();
PdfCopy pdf = new PdfCopy(document, stream);
PdfReader reader = null;
document.Open();
foreach (var item in listOfPathsToPDFs)
{
reader = new PdfReader(item);
pdf.AddDocument(reader);
reader.Close();
}
document.Close();
}
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();
}
I did generate a pdf file from jpg images. But the jpg images have the size of an official paper. When I open the pdf, the image is too big. I need that the pdf document is in official paper size. Any solution? (panel1 has the size of offical paper. I need that this size is equal of offical paper's size)
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "PDF Files|*.pdf";
string fileName = string.Empty;
saveFileDialog1.FileName = "name.pdf";
btnGerarPDF.Visible = false;
using (Bitmap bitmap = new Bitmap(panel1.ClientSize.Width,
panel1.ClientSize.Height))
{
panel1.DrawToBitmap(bitmap, panel1.ClientRectangle);
bitmap.Save("C:\\" + (nPaginasPDF + 1) + ".bmp", ImageFormat.Bmp);
}
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
fileName = saveFileDialog1.FileName;
Document doc = new Document();
PdfWriter.GetInstance(doc, new FileStream(fileName, FileMode.Create));
doc.Open();
for (int iCnt = 0; iCnt < nPaginasPDF+1; iCnt++)
{
iTextSharp.text.Image image1 = iTextSharp.text.Image.GetInstance("C:\\" + (iCnt + 1) + ".bmp");
image1.ScalePercent(75f);
doc.NewPage();
doc.Add(image1);
}
doc.Close();
}
You can set the pagesize when you create the document:
Document doc = new Document(PageSize.A4);
The following code prompts the user to select a path to save an image from the pictureBox:
Stream myStream;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "Portable Network Graphics|*.png";
saveFileDialog1.Title = "Bild speichern";
saveFileDialog1.RestoreDirectory = true;
saveFileDialog1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if ((myStream = saveFileDialog1.OpenFile()) != null)
{
this.picBox.Image.Save(myStream.ToString()); // is not getting the selected path
myStream.Close();
}
}
But how can I get the path from myStream or save the image to the user defined location (with compatibility to .NET 3.5)?
If you want to get the selected file path from the save dialog then use...
saveFileDialog1.FileName;
See here for more information on this property
You don't need to worry about using a Stream for this task.
Just to be clear, here is what your code should be...
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "Portable Network Graphics|*.png";
saveFileDialog1.Title = "Bild speichern";
saveFileDialog1.RestoreDirectory = true;
saveFileDialog1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
this.picBox.Image.Save(saveFileDialog1.FileName);
}
you can work with the SaveFileDialog.FileName only, no need for separated streams, try this:
using (var saveFileDialog1 = new SaveFileDialog())
{
saveFileDialog1.Filter = "Portable Network Graphics|*.png";
saveFileDialog1.Title = "Bild speichern";
saveFileDialog1.RestoreDirectory = true;
saveFileDialog1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
picBox.Image.Save(saveFileDialog1.FileName);
}
}
You can use:
string path = Path.GetDirectory(saveFileDialog1.Filename);
this.picBox.Image.Save(saveFileDialog1.Filename);
You really don't need a stream to do that :)
How's this?
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "Portable Network Graphics|*.png";
saveFileDialog1.Title = "Bild speichern";
saveFileDialog1.RestoreDirectory = true;
saveFileDialog1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
(using FileStream fStr = new FileStream(saveFileDialog1.FileName, FileMode.Create))
{
this.picBox.Image.Save(fStr);
fStr.Close();
}
}