Transform IText7 to base64 C# [duplicate] - c#

I am trying to get a pdf from datatable and attach it to an entity in CRM. For that purpose I use this code. Unfortunately created pdf is broken, I am unable to open it. Any ideas?
private static string ExportToBase64Pdf(DataTable dt, string entityName)
{
using (MemoryStream memoryStream = new MemoryStream())
{
Document document = new Document(PageSize.A4);
PdfWriter writer = PdfWriter.GetInstance(document, memoryStream);
document.Open();
Font font5 = FontFactory.GetFont(FontFactory.HELVETICA, 5);
PdfPTable table = new PdfPTable(dt.Columns.Count);
float[] widths = new float[dt.Columns.Count];
for (int i =0; i<dt.Columns.Count; i++) { widths[i] = 4f; }
table.SetWidths(widths);
table.WidthPercentage = 100;
PdfPCell cell = new PdfPCell(new Phrase(entityName));
cell.Colspan = dt.Columns.Count;
foreach (DataColumn c in dt.Columns)
{
table.AddCell(new Phrase(c.ColumnName, font5));
}
foreach (DataRow r in dt.Rows)
{
for (int i = 0; i < dt.Columns.Count; i++)
{
table.AddCell(new Phrase(r[i].ToString(), font5));
}
}
document.Add(table);
var bytes = memoryStream.ToArray();
var encodedPDF = Convert.ToBase64String(bytes);
document.Close();
return encodedPDF;
}
}

You retrieve the document bytes before the document is finished by closing:
var bytes = memoryStream.ToArray();
var encodedPDF = Convert.ToBase64String(bytes);
document.Close();
Move the close call before the ToArray call.

Related

How to combine multiple images into single pdf using iTextSharp

I have implemented the code but the problem is I am able to combine only one image into a single pdf but I want to combine multiple images into a single pdf. My code is:
public void ImagesToPdf(string[] imagepaths, string pdfpath)
{
using (var ms = new MemoryStream())
{
var srcImage = new Bitmap(imagepaths[0].ToString());
iTextSharp.text.Rectangle pageSize = new iTextSharp.text.Rectangle(0, 0, srcImage.Width, srcImage.Height);
var document = new iTextSharp.text.Document(pageSize, 0, 0, 0, 0);
iTextSharp.text.pdf.PdfWriter.GetInstance(document, ms).SetFullCompression();
document.Open();
var image = iTextSharp.text.Image.GetInstance(imagepaths[0].ToString());
document.Add(image);
document.Close();
File.WriteAllBytes(pdfpath, ms.ToArray());
}
}
Any suggestions will be of great help. Thank you
I have finally figured out how to do this task.
public static byte[] ConvertIntoSinglePDF(List<string> filePaths)
{
Document doc = new Document();
doc.SetPageSize(PageSize.A4);
var ms = new System.IO.MemoryStream();
{
PdfCopy pdf = new PdfCopy(doc, ms);
doc.Open();
foreach (string path in filePaths)
{
byte[] data = File.ReadAllBytes(path);
doc.NewPage();
Document imageDocument = null;
PdfWriter imageDocumentWriter = null;
switch (Path.GetExtension(path).ToLower().Trim('.'))
{
case "bmp":
case "gif":
case "jpg":
case "png":
imageDocument = new Document();
using (var imageMS = new MemoryStream())
{
imageDocumentWriter = PdfWriter.GetInstance(imageDocument, imageMS);
imageDocument.Open();
if (imageDocument.NewPage())
{
var image = iTextSharp.text.Image.GetInstance(data);
image.Alignment = Element.ALIGN_CENTER;
image.ScaleToFit(doc.PageSize.Width - 10, doc.PageSize.Height - 10);
if (!imageDocument.Add(image))
{
throw new Exception("Unable to add image to page!");
}
imageDocument.Close();
imageDocumentWriter.Close();
PdfReader imageDocumentReader = new PdfReader(imageMS.ToArray());
var page = pdf.GetImportedPage(imageDocumentReader, 1);
pdf.AddPage(page);
imageDocumentReader.Close();
}
}
break;
case "pdf":
var reader = new PdfReader(data);
for (int i = 0; i < reader.NumberOfPages; i++)
{
pdf.AddPage(pdf.GetImportedPage(reader, i + 1));
}
pdf.FreeReader(reader);
reader.Close();
break;
default:
break;
}
}
if (doc.IsOpen()) doc.Close();
return ms.ToArray();
}
}
Once you got the byte array then just just write all bytes into file like this
byte[] document= ImagesToPDF.ConvertIntoSinglePDF(images);
File.WriteAllBytes("cheque.pdf", document);
ASP.NET C# Code Less
string FileNamePdf = PdfFileName.Text;
Document document = new iTextSharp.text.Document(PageSize.A4, 10f, 10f, 10f, 10f);
var output = new FileStream(Path.Combine(ObjData.ParentFolderPath + "\\SaveLocation", FileNamePdf + ".pdf"), FileMode.Create);
var writer = PdfWriter.GetInstance(document, output);
document.Open();
foreach (HttpPostedFile file in FilesToConvert.PostedFiles)
{
Image image = iTextSharp.text.Image.GetInstance(file.InputStream);
image.ScaleAbsolute(575f, 820.25f);
document.Add(image);
writer.NewPage();
}
document.Close();

itextSharp datatable to pdf base64 string - pdf damaged

I am trying to get a pdf from datatable and attach it to an entity in CRM. For that purpose I use this code. Unfortunately created pdf is broken, I am unable to open it. Any ideas?
private static string ExportToBase64Pdf(DataTable dt, string entityName)
{
using (MemoryStream memoryStream = new MemoryStream())
{
Document document = new Document(PageSize.A4);
PdfWriter writer = PdfWriter.GetInstance(document, memoryStream);
document.Open();
Font font5 = FontFactory.GetFont(FontFactory.HELVETICA, 5);
PdfPTable table = new PdfPTable(dt.Columns.Count);
float[] widths = new float[dt.Columns.Count];
for (int i =0; i<dt.Columns.Count; i++) { widths[i] = 4f; }
table.SetWidths(widths);
table.WidthPercentage = 100;
PdfPCell cell = new PdfPCell(new Phrase(entityName));
cell.Colspan = dt.Columns.Count;
foreach (DataColumn c in dt.Columns)
{
table.AddCell(new Phrase(c.ColumnName, font5));
}
foreach (DataRow r in dt.Rows)
{
for (int i = 0; i < dt.Columns.Count; i++)
{
table.AddCell(new Phrase(r[i].ToString(), font5));
}
}
document.Add(table);
var bytes = memoryStream.ToArray();
var encodedPDF = Convert.ToBase64String(bytes);
document.Close();
return encodedPDF;
}
}
You retrieve the document bytes before the document is finished by closing:
var bytes = memoryStream.ToArray();
var encodedPDF = Convert.ToBase64String(bytes);
document.Close();
Move the close call before the ToArray call.

Add Table to PdfStamper.AcroFields iTextSharp

I am getting started working with iTextSharp and am having trouble doing something pretty straightforward. I have a template that I am populating with PdfStamper like so
PdfReader rdr = new PdfReader(#"C:\temp\Template.pdf");
PdfStamper stamper = new PdfStamper(rdr, new System.IO.FileStream(path = #"C:\temp\Created.pdf", System.IO.FileMode.Create));
stamper.AcroFields.SetField("softwarename", "Software");
stamper.FormFlattening = true;
AcroFields form = stamper.AcroFields;
form.GenerateAppearances = true;
stamper.Close();
rdr.Close();
I want to be able to have a field called "grid" or something like that, and populate it with a PdfPTable with all the formatting intact (I know I can do it all in strings, but I don't want that). Is there a preferred way to do this?
The PDFStamper documentation says that it takes all objects allowed, so I would use a combination of objects (or lists of objects) and flags. That way you can pass in all the info you need an manipulate it according the whatever logic you need.
The following code will place images in a grid equally across the top of the page using the PdfPTable.
Then you can use PdfTemplate and use the WriteSelectedRows method to write the contents of the PdfPTable to it.
PdfPTable table;
string inputFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "input.pdf");
string outputFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "output.pdf");
List<ImageTextSharpModel> images
PdfPTable table = new PdfPTable(images.Count);
table.WidthPercentage = 100;
table.HorizontalAlignment = Element.ALIGN_RIGHT;
for (var i = 0; i < images.Count; i++)
{
var image = images[i];
try
{
PdfPCell cell = new PdfPCell();
cell.BorderWidth = 0;
cell.FixedHeight = image.Height;
cell.VerticalAlignment = Element.ALIGN_MIDDLE;
Paragraph p = new Paragraph();
float offset = 0;
var img = iTextSharp.text.Image.GetInstance(image.AbsolutePath);
img.ScaleToFit(image.Width, image.Height);
//Manually setting the location
if (image.Alignment == iTextSharp.text.Image.RIGHT_ALIGN)
{
offset = i == 0
? (((doc.PageSize.Width/images.Count) - doc.LeftMargin) - img.ScaledWidth)
: (((doc.PageSize.Width/images.Count) - doc.LeftMargin) - img.ScaledWidth) - cell.Width;
}
else if (image.Alignment == iTextSharp.text.Image.ALIGN_CENTER)
{
if (images.Count == 1)
{
offset = ((doc.PageSize.Width - img.ScaledWidth)/2) - doc.LeftMargin;
}
else
{
offset = (((doc.PageSize.Width/images.Count) - img.ScaledWidth)/2);
}
}
p.Add(new Chunk(img, offset, 0));
cell.AddElement(p);
table.AddCell(cell);
}
catch (Exception ex)
{
//Ignore
}
}
;
//add table to stamper
iTextSharp.text.pdf.PdfReader pdfReader = new iTextSharp.text.pdf.PdfReader(inputFile);
using (FileStream fs = new FileStream(outputFile, FileMode.Create, FileAccess.Write, FileShare.None))
{
using (PdfStamper stamper = new PdfStamper(pdfReader, fs))
{
int PageCount = pdfReader.NumberOfPages;
for (int x = 1; x <= PageCount; x++)
{
PdfContentByte canvas = stamper.GetOverContent(x);
PdfTemplate tableTemplate = canvas.CreateTemplate(1500, 1300);
table.WriteSelectedRows(0, -1, 0, 1300, tableTemplate);
}
stamper.Close();
}
}

It is possible to cut an image of ItextSharp.Text.Image?

I'm creating a pdf file from an large image, but my image is too large, and it does not fit in the only page. then i need split this image to create more pages.
any idea?
public FileResult ResultadoParaPdf(string file)
{
string fileStringReplace = file.Replace("data:image/png;base64,", "");
var image = Convert.FromBase64String(fileStringReplace);
const int HorizontalMargin = 40;
const int VerticalMargin = 40;
using (var outputMemoryStream = new MemoryStream())
{
using (var pdfDocument = new Document(PageSize.A4, HorizontalMargin, HorizontalMargin, VerticalMargin, VerticalMargin))
{
iTextSharp.text.pdf.PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDocument, outputMemoryStream);
pdfWriter.CloseStream = false;
pdfDocument.Open();
PdfPTable table = new PdfPTable(1);
table.WidthPercentage = 100;
Image img = Image.GetInstance(image);
img.WidthPercentage = 100;
PdfPCell c = new PdfPCell(img, true);
c.Border = PdfPCell.NO_BORDER;
c.Padding = 5;
c.Image.ScaleToFit(750f, 750f);
table.AddCell(c);
pdfDocument.Add(table);
pdfDocument.Close();
byte[] created = outputMemoryStream.ToArray();
outputMemoryStream.Write(created, 0, created.Length);
outputMemoryStream.Position = 0;
return File(created, "application/pdf", "teste.pdf");
}
}
}

Save Pdf in Zip with MemoryStream

I try the save multiples files pdf in zip but I can't, can somebody can help me?
using (MemoryStream memorystream = new MemoryStream())
{
string zip = #"C:\Temp\ZipFile.zip";
using (var archive = new ZipArchive(memorystream, ZipArchiveMode.Create, true))
{
for (int i = 0; i < 1; i++)
{
ZipArchiveEntry file = archive.CreateEntry(string.Format("Test{0}.pdf", i), CompressionLevel.Optimal);
using (Stream stream = file.Open())
{
Document document = new Document(PageSize.A4, 25, 25, 30, 30);
PdfWriter writer = PdfWriter.GetInstance(document, memorystream);
document.Open();
//
PdfPTable table = new PdfPTable(7);
Font fdefault = FontFactory.GetFont("Arial", 9, Font.NORMAL, BaseColor.DARK_GRAY);
table.AddCell(new Paragraph("Container", fdefault));
table.AddCell(new Paragraph("Code", fdefault));
table.AddCell(new Paragraph("ITEM", fdefault));
table.AddCell(new Paragraph("Reference", fdefault));
table.AddCell(new Paragraph("Description", fdefault));
table.AddCell(new Paragraph("Size", fdefault));
table.AddCell(new Paragraph("Quantity", fdefault));
document.Add(table);
document.Close();
writer.Close();
memorystream.Close();
}
}
}
using (var fileStream = new FileStream(zip, FileMode.Create))
{
memorystream.Seek(0, SeekOrigin.Begin);
memorystream.CopyTo(fileStream);
}
}
I do it that with ExcelPackage and work but this don't work, I don't know the problem. I would appreciate if anyone can help me with this problem.
You've got two fatal flaws.
First, you are binding the PdfWriter to the zip's MemoryStream instead of the Stream that you are getting back from ZipArchiveEntry.Open(). So change this line:
PdfWriter writer = PdfWriter.GetInstance(document, memorystream);
To this:
PdfWriter writer = PdfWriter.GetInstance(document, stream);
Second but related to the first, you are closing the zip's MemoryStream inside of the for loop. Just kill off the line:
memorystream.Close();
Putting that all together and switching over to the preferred using pattern you get this:
using (var zipMemorystream = new MemoryStream())
{
using (var archive = new ZipArchive(zipMemorystream, ZipArchiveMode.Create, true))
{
for (int i = 0; i < 10; i++)
{
var file = archive.CreateEntry(string.Format("Test{0}.pdf", i), CompressionLevel.Optimal);
using (Stream stream = file.Open( ))
{
using( var document = new Document(PageSize.A4, 25, 25, 30, 30) )
{
using( var writer = PdfWriter.GetInstance(document, stream))
{
document.Open();
//
var table = new PdfPTable(7);
var fdefault = FontFactory.GetFont("Arial", 9, iTextSharp.text.Font.NORMAL, BaseColor.DARK_GRAY);
table.AddCell(new Paragraph("Container", fdefault));
table.AddCell(new Paragraph("Code", fdefault));
table.AddCell(new Paragraph("ITEM", fdefault));
table.AddCell(new Paragraph("Reference", fdefault));
table.AddCell(new Paragraph("Description", fdefault));
table.AddCell(new Paragraph("Size", fdefault));
table.AddCell(new Paragraph("Quantity", fdefault));
document.Add(table);
document.Close();
}
}
}
}
}
string zip = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "ZipFile.zip");
using (var fileStream = new FileStream(zip, FileMode.Create))
{
zipMemorystream.Seek(0, SeekOrigin.Begin);
zipMemorystream.CopyTo(fileStream);
}
}

Categories

Resources