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);
Related
I’m using WebSite in ASP.NET and iTextSharp PDF library. I have a tiff document image that contains 3 pages, I would want to convert all those 3 tiff pages into 1 PDF file with 3 pages.
I try this but it doesn't work as well...
Please tell me what should I do?
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;
Document document = new Document();
using (var stream = new FileStream(#"C:\File\0.pdf", FileMode.Create, FileAccess.Write, FileShare.None))
{
PdfWriter.GetInstance(document, stream);
document.Open();
using (var imageStream = new FileStream(#"C:\File\0.tiff", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
var image = iTextSharp.text.Image.GetInstance(imageStream);
document.Add(image);
}
document.Close();
}
// creation of the document with a certain size and certain margins
iTextSharp.text.Document document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 0, 0, 0, 0);
// creation of the different writers
iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, new System.IO.FileStream(Server.MapPath("~/App_Data/result.pdf"), System.IO.FileMode.Create));
// load the tiff image and count the total pages
System.Drawing.Bitmap bm = new System.Drawing.Bitmap(Server.MapPath("~/App_Data/source.tif"));
int total = bm.GetFrameCount(System.Drawing.Imaging.FrameDimension.Page);
document.Open();
iTextSharp.text.pdf.PdfContentByte cb = writer.DirectContent;
for (int k = 0; k < total; ++k)
{
bm.SelectActiveFrame(System.Drawing.Imaging.FrameDimension.Page, k);
iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(bm, System.Drawing.Imaging.ImageFormat.Bmp);
// scale the image to fit in the page
img.ScalePercent(72f / img.DpiX * 100);
img.SetAbsolutePosition(0, 0);
cb.AddImage(img);
document.NewPage();
}
document.Close();
I just copied the code from this answer, and modified it to your example. So credits go to the person who answered the question in the link.
using (var stream = new FileStream(#"C:\File\0.pdf", FileMode.Create, FileAccess.Write, FileShare.None))
{
Document document = new Document(PageSize.A4, 0, 0, 0, 0);
var writer = PdfWriter.GetInstance(document, stream);
var bitmap = new System.Drawing.Bitmap(#"C:\File\0.tiff");
var pages = bitmap.GetFrameCount(System.Drawing.Imaging.FrameDimension.Page);
document.Open();
iTextSharp.text.pdf.PdfContentByte cb = writer.DirectContent;
for (int i = 0; i < pages; ++i)
{
bitmap.SelectActiveFrame(System.Drawing.Imaging.FrameDimension.Page, i);
iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(bitmap, System.Drawing.Imaging.ImageFormat.Bmp);
// scale the image to fit in the page
//img.ScalePercent(72f / img.DpiX * 100);
//img.SetAbsolutePosition(0, 0);
cb.AddImage(img);
document.NewPage();
}
}
document.Close();
}
What I achieved after a long period and based on some searches.
I make a request and the response is PDF or TIFF. The first part is just what I get and how I call the private methods, and that is what you need.
var httpResponse = (HttpWebResponse)(await httpWebRequest.GetResponseAsync());
Stream stream = httpResponse.GetResponseStream();
string contentType = httpResponse.ContentType;
MemoryStream ms = new MemoryStream();
stream.CopyTo(ms);
FileStream file2;
try
{
switch (contentType)
{
case "application/pdf":
{
string outputfile2 = Path.Combine(zipDirectory, "ixosid_" + icxos + ".pdf");
file2 = new FileStream(outputfile2, FileMode.Create, FileAccess.Write);
ms.WriteTo(file2);
file2.Close();
break;
}
default:
{
string outputfile1 = Path.Combine(zipDirectory, "ixosid_" + icxos + ".tiff");
file2 = new FileStream(outputfile1, FileMode.Create, FileAccess.Write);
ms.WriteTo(file2);
file2.Close();
string[] outfilesTiffPages = ConvertTiffToJpeg(outputfile1);
File.Delete(outputfile1);
string outputfile2 = Path.Combine(zipDirectory, "ixosid_" + icxos + ".pdf");
iTextSharp.text.Document doc= AddPicturesToPDF(outfilesTiffPages, outputfile2);
break;
}
}
}
and I have two private methods
private string[] ConvertTiffToJpeg(string fileName)
{
using (System.Drawing.Image imageFile = System.Drawing.Image.FromFile(fileName))
{
FrameDimension frameDimensions = new FrameDimension(
imageFile.FrameDimensionsList[0]);
// Gets the number of pages from the tiff image (if multipage)
int frameNum = imageFile.GetFrameCount(frameDimensions);
string[] jpegPaths = new string[frameNum];
for (int frame = 0; frame < frameNum; frame++)
{
// Selects one frame at a time and save as jpeg.
imageFile.SelectActiveFrame(frameDimensions, frame);
using (Bitmap bmp = new Bitmap(imageFile))
{
jpegPaths[frame] = String.Format(#"{0}\{1}{2}.jpg",
Path.GetDirectoryName(fileName),
Path.GetFileNameWithoutExtension(fileName),
frame);
bmp.Save(jpegPaths[frame], ImageFormat.Jpeg);
}
}
return jpegPaths;
}
}
private iTextSharp.text.Document AddPicturesToPDF(string[] filesPaths, string outputPdf)
{
FileStream fs = new FileStream(outputPdf, FileMode.Create);
Document pdfdoc = new Document();
PdfWriter.GetInstance(pdfdoc, fs);
pdfdoc.Open();
int size = filesPaths.Length;
int count = 0;
foreach(string imagePath in filesPaths)
{
iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(imagePath);
img.Alignment = Element.ALIGN_CENTER;
img.SetAbsolutePosition(0, 0);
img.ScaleToFit((PageSize.A4.Width - pdfdoc.RightMargin - pdfdoc.LeftMargin), (PageSize.A4.Height- pdfdoc.BottomMargin - pdfdoc.TopMargin));
pdfdoc.Add(img);
pdfdoc.NewPage();
}
pdfdoc.Close();
return pdfdoc;
}
Maybe I can work with MemoryStream but for now, is working and is what I need.
I searched a lot, and some links that deserve to be mentioned
https://coderedirect.com/questions/178295/convert-tiff-to-jpg-format
I have this code that will add a watermark on each page:
string watermarkLocation = AppDomain.CurrentDomain.BaseDirectory + "Watermark.png";
Document document = new Document();
PdfReader pdfReader = new PdfReader(fileLocation);
PdfStamper stamp = new PdfStamper(pdfReader, new FileStream(fileLocation.Replace(".pdf", "_marked.pdf"), FileMode.Create));
iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(watermarkLocation);
img.ScaleToFit(document.PageSize);
img.SetAbsolutePosition(0, 100);
PdfContentByte waterMark;
for (int page = 1; page <= pdfReader.NumberOfPages; page++)
{
waterMark = stamp.GetOverContent(page);
waterMark.AddImage(img);
}
stamp.FormFlattening = true;
stamp.Close();
return fileLocation.Replace(".pdf", "_marked.pdf");
But on PDFs that have textboxes, the image will go behind the textbox/form. I thought flattening the file will fix this, but it does not work.
I used a full image as a test but the watermark in the end will have transparency.
Here's the final code I'm using. As my comment mentioned, there's basically 2 readers/stamps, one to flatten the file and another to add the watermark.
Flatten file:
private byte[] FlattenPdfFormToBytes(PdfReader reader)
{
var memStream = new MemoryStream();
var stamper = new PdfStamper(reader, memStream) { FormFlattening = true };
stamper.Close();
return memStream.ToArray();
}
Add Watermark (which will call FlattenPdfFormToBytes):
public string AddWatermark(string fileLocation)
{
string watermarkLocation = AppDomain.CurrentDomain.BaseDirectory + "Watermark.png";
Document document = new Document();
PdfReader pdfReader = new PdfReader(fileLocation);
PdfReader pdfFlatten = new PdfReader(FlattenPdfFormToBytes(pdfReader)); // The secret sauce is this!!!
PdfStamper stamp = new PdfStamper(pdfFlatten, new FileStream(fileLocation.Replace(".pdf", "_marked.pdf"), FileMode.Create));
iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(watermarkLocation);
img.ScaleToFit(document.PageSize);
img.SetAbsolutePosition(0, 100);
PdfContentByte waterMark;
for (int page = 1; page <= pdfFlatten.NumberOfPages; page++)
{
waterMark = stamp.GetOverContent(page);
waterMark.AddImage(img);
}
stamp.Close();
return fileLocation.Replace(".pdf", "_marked.pdf");
}
i have a pdf file. There is a footer on each page. now i want to replace a static text exist on footer with some other text. Please Help me.....
I have tried with following case but not success
PdfReader readere = new PdfReader(#"D:\MergedOutput.pdf");
for (int i = 1; i < readere.NumberOfPages; i++)
{
byte[] contentBytes = PdfEncodings.ConvertToBytes(PdfTextExtractor.GetTextFromPage(readere, i), PdfObject.TEXT_PDFDOCENCODING);
byte[] searchStringArray = PdfEncodings.ConvertToBytes("Side", PdfObject.TEXT_PDFDOCENCODING);
byte[] replacedByString = PdfEncodings.ConvertToBytes("Hello", PdfObject.TEXT_PDFDOCENCODING);
string searchString = PdfEncodings.ConvertToString(searchStringArray, PdfObject.TEXT_PDFDOCENCODING);
string contentString = PdfEncodings.ConvertToString(contentBytes, PdfObject.TEXT_PDFDOCENCODING);
string replaceString = PdfEncodings.ConvertToString(replacedByString, PdfObject.TEXT_PDFDOCENCODING);
if (contentString.Contains(searchString))
{
contentString = contentString.Replace(searchString, replaceString);
}
readere.SetPageContent(i, PdfEncodings.ConvertToBytes(contentString, PdfObject.TEXT_PDFDOCENCODING));
}
Suppose you have a byte array of PDF data or any PDF files. First convert this file to byte array.. after that we have to apply below code section. its working fine for me...
iTextSharp.text.Font blackFont = FontFactory.GetFont("Seoge UI", 10, iTextSharp.text.Font.NORMAL, new BaseColor(Color.FromArgb(97, 102, 116)));
//Path to where you want the file to output
string outputFilePath = "MergedOutputt.pdf";
//Path to where the pdf you want to modify is
//string inputFilePath = "D:\\MergedOutput.pdf";
try
{
using (Stream outputPdfStream = new FileStream(outputFilePath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
using (Stream outputPdfStream2 = new FileStream(outputFilePath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))
{
//Opens the unmodified PDF for reading
var reader = new PdfReader(MergedOutputStream.ToArray());
//Creates a stamper to put an image on the original pdf
var stamper = new PdfStamper(reader, outputPdfStream) { FormFlattening = true, FreeTextFlattening = true };
for (int i = 1; i <= reader.NumberOfPages; i++)
{
//Creates an image that is the size i need to hide the text i'm interested in removing
iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(new Bitmap(120, 20), BaseColor.WHITE);
//Sets the position that the image needs to be placed (ie the location of the text to be removed)
image.SetAbsolutePosition(reader.GetPageSize(i).Width - 120, 42);
//Adds the image to the output pdf
stamper.GetOverContent(i).AddImage(image, true);
//Creates the first copy of the outputted pdf
PdfPTable table = new PdfPTable(1);
float[] width = new float[] { 38 };
table.SetTotalWidth(width);
PdfContentByte pb;
//Get PdfContentByte object for first page of pdf file
pb = stamper.GetOverContent(i);
cellSequenceNumber = new PdfPCell(new Phrase(new Chunk("Side " + i.ToString(), blackFont)));
cellSequenceNumber.Border = 0;
table.AddCell(cellSequenceNumber);
table.WriteSelectedRows(0, table.Rows.Count, reader.GetPageSize(i).Width - 82, 54, pb);
}
stamper.Close();
//Opens our outputted file for reading
var reader2 = new PdfReader(outputPdfStream2);
reader2.Close();
}
}
It will generate a pdf file named as "MergedOutputt.pdf"
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...
I have a problem to create a pdf with itextsharp from images in .tiff.
Here is some code :
iTextSharp.text.Document d = new iTextSharp.text.Document();
PdfWriter pw = PdfWriter.GetInstance(d, new FileStream(filename, FileMode.Create));
d.Open();
PdfContentByte cb = pw.DirectContent;
foreach (Image img in imgs)
{
d.NewPage();
d.SetPageSize(new iTextSharp.text.Rectangle(0, 0, img.Width, img.Height));
iTextSharp.text.Image timg = iTextSharp.text.Image.GetInstance(img, iTextSharp.text.BaseColor.WHITE);
timg.SetAbsolutePosition(0, 0);
cb.AddImage(timg);
cb.Stroke();
}
d.Close();
It creates the pdf with two pages but the image on the first page is to big.The page have the size of the image but it zoom an the bottom left corner of the image.
It does that only with the tiff image, if I take png, it works fine.
Any solution?
Thanks to the comment of mkl, I found it.
Set the page size (SetPageSize) before the new page command (NewPage)
use like this
string[] validFileTypes = {"tiff"};
string ext = System.IO.Path.GetExtension(FileUpload1.PostedFile.FileName);
bool isValidFile = false;
if (!isValidFile)
{
Label.Text = "Invalid File. Please upload a File with extension " +
string.Join(",", validFileTypes);
}
else
{
string pdfpath = Server.MapPath("pdf");
Document doc = new Document(PageSize.A4, 0f, 0f, 0f, 0f);
PdfWriter.GetInstance(doc, new FileStream(pdfpath + "/Images.pdf", FileMode.Create));
doc.Open();
string savePath = Server.MapPath("images\\");
if (FileUpload1.PostedFile.ContentLength != 0)
{
string path = savePath + FileUpload1.FileName;
FileUpload1.SaveAs(path);
iTextSharp.text.Image tiff= iTextSharp.text.Image.GetInstance(path);
tiff.ScaleToFit(doc.PageSize.Width, doc.PageSize.Height);
tiff.SetAbsolutePosition(0,0);
PdfPTable table = new PdfPTable(1);
table.AddCell(new PdfPCell(tiff));
doc.Add(table);
}
doc.Close();
}