itextSharp datatable to pdf base64 string - pdf damaged - 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

Merge PDF File Using itextsharp and byte Array From Database

I am creating one PDF from iTextSharp, and I have 4 PDF file store in database in Binary Format.
I have to merge these file into single PDF.
My final PDF only contains PDFs from database and also 1st PDF from database gets repeated. Following is my code:
Byte[] bytesdoc = null;
Byte[] bytesdoc1 = null;
Sdetails FileExt = new Sdetails();
bytesdoc = FileExt.creatPDFProfile(lblApplicationno.Text);
Tuple<int, DataTable> _GetFile = GetFile(lblApplicationno.Text);
if ( int.Parse(_GetFile.Item1.ToString())==1)
{
DataTable dt = new DataTable();
dt.Columns.Add("DocumenrFile", typeof(byte[]));
byte[] imageByte = null;
imageByte = bytesdoc;
DataRow drNew = dt.NewRow();
drNew["DocumenrFile"] = imageByte;
dt.Rows.Add(drNew);
for (int j = 0; j < _GetFile.Item2.Rows.Count; j++)
{
bytesdoc = Combine(_GetFile.Item2.Rows[j]["DocumenrFile"] as byte[]);
//dt.Rows.Add(drNew.ItemArray);
}
// bytesdoc1 = Combine();
DataTable dtClubNotings = dt;
//DataTable dtClubNotings = _GetFile.Item2;
if (dtClubNotings.Rows.Count > 0)
{
System.IO.MemoryStream m = new System.IO.MemoryStream();
iTextSharp.text.Document doc = new iTextSharp.text.Document();
doc.AddTitle(lblApplicationno.Text);
PdfCopy pdf = new PdfCopy(doc, m);
doc.Open();
PdfReader reader;
for (int i = 0; i < dtClubNotings.Rows.Count; i++)
{
reader = new PdfReader(dtClubNotings.Rows[i]["DocumenrFile"] as byte[]);
int noofPages = reader.NumberOfPages;
for (int j = 1; j <= noofPages; j++)
{
PdfImportedPage importedPage = pdf.GetImportedPage(reader, j);
pdf.AddPage(importedPage);
}
}
doc.Close();
byte[] result;
result = m.ToArray();
byte[] _byte2 = (byte[])result;
Response.Buffer = true;
Response.AppendHeader("Content-Disposition", "attachment; filename=Profile_Print.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/pdf";
Response.BinaryWrite(bytesdoc.ToArray());
Response.Flush();
}
}
// Get Database File
Tuple<int, DataTable> GetFile(string _AppNo)
{
int returnval = 0;
DataTable _ds = new DataTable();
SqlConnection _cn = _obj.SqlconnectionHousing();
_cn.Open();
SqlCommand _cmd = new SqlCommand(#"select DocumenrFile from tblApplicationDocument where applicationNo=#applicationNo and DocumentId<>'001'", _cn);
_cmd.Parameters.AddWithValue("#applicationNo", _AppNo);
SqlDataAdapter da = new SqlDataAdapter(_cmd);
da.Fill(_ds);
if (_ds.Rows.Count > 0)
{
returnval = 1;
}
da.Dispose();
_ds.Dispose();
_cmd.Dispose();
_cn.Close();
_cn.Dispose();
return new Tuple<int, DataTable>(returnval,_ds);
}
I am creating one PDF from iTextSharp, and I have 4 PDF file store in database in Binary Format.
I have to merge these file into single PDF.
My final PDF only contains PDFs from database and also 1st PDF from database gets repeated.

Transform IText7 to base64 C# [duplicate]

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