iTextSharp Image minimum Table cell height - c#

I am trying to append images to a PDF document, but the image width must = doc.PageSize.Width and height in ratio with the image width.
I am appending individual images, each in its own table and in a cell using the following method
public void AddImage(Document doc, iTextSharp.text.Image Image)
{
PdfPTable table = new PdfPTable(1);
table.WidthPercentage = 100;
table.TotalWidth = doc.PageSize.Width;
PdfPCell c = new PdfPCell(Image, true);
c.Border = PdfPCell.NO_BORDER;
c.Padding = 5;
c.FixedHeight = (doc.PageSize.Width / Image.Width) * Image.Height;
c.MinimumHeight = (doc.PageSize.Width / Image.Width) * Image.Height;
table.AddCell(c);
doc.Add(table);
}
The Document code part (Do not think this is necessary though):
using (PDFBuilder pdf = new PDFBuilder())
{
using (var doc = new Document())
{
PdfWriter writer = PdfWriter.GetInstance(doc, Response.OutputStream);
doc.Open();
var image = iTextSharp.text.Image.GetInstance(Request.MapPath("~/Images/Nemo.jpg"));
pdf.AddImage(doc, image);
pdf.AddImage(doc, image);
pdf.AddImage(doc, image);
}
}
What I want is for the images to be 100% width, and if not, the image must append on the next page.
This is currently what I am getting
And this is what I want
Any help would be greatly appreciated, thank you in advance!

Got It!
This line needed to be added:
c.Image.ScaleToFitHeight = false;
My Method
public void AddImage(Document doc, iTextSharp.text.Image Image)
{
PdfPTable table = new PdfPTable(1);
table.WidthPercentage = 100;
PdfPCell c = new PdfPCell(Image, true);
c.Border = PdfPCell.NO_BORDER;
c.Padding = 5;
c.Image.ScaleToFitHeight = false; /*The new line*/
table.AddCell(c);
doc.Add(table);
}

Related

image displays size issue [duplicate]

This question already has answers here:
How to resize an iTextSharp.text.Image size into my code?
(3 answers)
Closed 8 years ago.
I am trying to display some images in pdf using iTextSharp.Its working fine but my problem is, some images displays in zooming from its actual size like below image,
The code I tried to display is,
iTextSharp.text.Font fontH1 = new iTextSharp.text.Font(Currier, 18, iTextSharp.text.Font.BOLD);
Document doc1 = new Document();
string path1 = Environment.GetFolderPath(Environment.SpecialFolder.CommonDocuments);
path1 = path1 + "\\DOC\\Mathematicsquestions.pdf";
iTextSharp.text.Rectangle pageSize1 = doc1.PageSize;
PdfWriter pdf = PdfWriter.GetInstance(doc1, new FileStream(path1, FileMode.Create));
doc1.Open();
pdf.Open();
PdfPTable table = new PdfPTable(2);
//actual width of table in points
table.TotalWidth = 500f;
//fix the absolute width of the table
table.LockedWidth = true;
//relative col widths in proportions - 1/3 and 2/3
float[] widths = new float[] { 0.15f, 2.5f };
table.SetWidths(widths);
table.HorizontalAlignment = 0;
//leave a gap before and after the table
table.SpacingBefore = 0f;
table.SpacingAfter = 0f;
PdfPCell cell = new PdfPCell(new Phrase("MATHEMATICS", fontH1));
cell.Colspan = 2;
cell.Border = 0;
cell.HorizontalAlignment = 1;
table.AddCell(cell);
PdfPCell cell1 = new PdfPCell(new Phrase(" "));
cell1.Colspan = 2;
cell1.Border = 0;
cell1.HorizontalAlignment = 1;
table.AddCell(cell1);
for (int i = 0; i < mach.Count; i++)
{
string temsub = mach[i].ToString();
var quepaper1 = from fm in en.Entrance_jee where fm.En_Chapter == temsub select fm;
foreach (Entrance_jee re in quepaper1)
{
if (newsno == 0)
{
newsno = 1;
}
else
{
newsno = newsno + 1;
}
if (re.En_Isimage == true)
{
imgepath = path + re.En_Questionpage1 + ".png";
imgepath2 = path + re.En_Answer + ".png";
filename = System.IO.Path.GetFileName(imgepath);
filename2 = System.IO.Path.GetFileName(imgepath2);
decfile = decfile1 + "\\R1\\CF\\" + filename;
decfile2 = decfile1 + "\\R1\\CF\\" + filename2;
string status = encobj.DecryptFile(imgepath, decfile);
status = encobj.DecryptFile(imgepath2, decfile2);
if (status == "decrypted")
{
byte[] file = File.ReadAllBytes(decfile);
File.Delete(decfile);
iTextSharp.text.Image img1 = iTextSharp.text.Image.GetInstance(file);
byte[] file2 = File.ReadAllBytes(decfile2);
File.Delete(decfile2);
iTextSharp.text.Image img2 = iTextSharp.text.Image.GetInstance(file2);
//iTextSharp.text.pdf.PdfPCell imgCell1 = new iTextSharp.text.pdf.PdfPCell();
//imgCell1.AddElement(new Chunk(img2, 0, 0));
table.AddCell(newsno.ToString());
table.AddCell(img1);
table.AddCell(" ");
table.AddCell(img2);
}
}
else
{
table.AddCell(newsno.ToString());
table.AddCell(re.En_Questionpage1.ToString());
table.AddCell(" ");
table.AddCell(re.En_Answer.ToString());
}
}
}
doc1.Add(table);
doc1.Close();
Updated : Here is my orginal images,
Someone tell me where I am wrong?
The image appears to be scaled to the full width of the table. You need to scale it to your exact size requirements.
Try something like
iTextSharp.text.Image img1 = iTextSharp.text.Image.GetInstance(file);
iTextSharp.text.Image img2 = iTextSharp.text.Image.GetInstance(file2);
img1.ScaleToFit(500f, 37f);
img2.ScaleToFit(81f, 36f);
Or alternatively you can add a container within the cell with the required dimensions and add the image to it. See full details on - http://www.mikesdotnetting.com/article/87/itextsharp-working-with-images

iTextSharp SetCharacterSpacing broken when using Right Align

I have a table with two cells. The first cell is left aligned and the second cell is right aligned. I also want to change the character spacing of the text. I have found that changing the character spacing breaks the alignment so the right align text ends up outside the boundaries if the table.
I have created some test code below and the link to the output PDF is in this link
https://skydrive.live.com/redir?resid=1ECE2061CFF9124B!190&authkey=!ANcB0z_BN3N4UFo
Are there any alternatives or workarounds to getting the character spacing working well with the right alignment?
public void CharacterSpacingTest()
{
float margin = 50;
using (var stream = new MemoryStream())
{
Document document = new Document();
document.SetPageSize(new Rectangle(PageSize.A4.Width, PageSize.A4.Height));
document.SetMargins(margin, margin, 30f, 100f);
PdfWriter writer = PdfWriter.GetInstance(document, stream);
writer.CloseStream = false;
document.Open();
PdfPTable table = new PdfPTable(new float[] { 100 });
table.TotalWidth = PageSize.A4.Width - margin - margin;
table.WidthPercentage = 100f;
table.LockedWidth = true;
// Create a row that is right aligned
PdfPCell cell1 = new PdfPCell();
cell1.AddElement(new Paragraph("Hello World") { Alignment = Element.ALIGN_RIGHT });
cell1.BorderWidth = 1;
table.AddCell(cell1);
// Change the character spacing
PdfContentByte cb = writer.DirectContent;
cb.SetCharacterSpacing(1f);
// Create a row that is left aligned
PdfPCell cell2 = new PdfPCell();
cell2.AddElement(new Paragraph("Hello World"));
cell2.BorderWidth = 1;
table.AddCell(cell2);
document.Add(table);
document.Close();
Blobs.SaveToFile(Blobs.LoadFromStream(stream), #"c:\Dev\test.pdf");
}
}
I have managed to fix it by using chunks to set the character spacing. See amended code.
public void CharacterSpacingTest()
{
float margin = 50;
using (var stream = new MemoryStream())
{
Document document = new Document();
document.SetPageSize(new Rectangle(PageSize.A4.Width, PageSize.A4.Height));
document.SetMargins(margin, margin, 30f, 100f);
PdfWriter writer = PdfWriter.GetInstance(document, stream);
writer.CloseStream = false;
document.Open();
PdfPTable table = new PdfPTable(new float[] { 100 });
table.TotalWidth = PageSize.A4.Width - margin - margin;
table.WidthPercentage = 100f;
table.LockedWidth = true;
// Create a row that is right aligned
PdfPCell cell1 = new PdfPCell();
cell1.AddElement(new Paragraph(GetChunk("Hello World")) { Alignment = Element.ALIGN_RIGHT });
cell1.BorderWidth = 1;
table.AddCell(cell1);
// Create a row that is left aligned
PdfPCell cell2 = new PdfPCell();
cell2.AddElement(new Paragraph(GetChunk("Hello World")));
cell2.BorderWidth = 1;
table.AddCell(cell2);
document.Add(table);
document.Close();
Blobs.SaveToFile(Blobs.LoadFromStream(stream), #"c:\Dev\test.pdf");
}
}
private Chunk GetChunk(string text)
{
Chunk chunk = new Chunk(text);
chunk.SetCharacterSpacing(1);
return chunk;
}

itextsharp pdf page border?

I am using itext sharp for creating reports in PDF format.
I want page borders. I tried some ways. I am not successful.
How can I get a page border for top, bottom, left, right using iText for .NET?
I added one image 1. I want borders like described in the image.
You can try this code for adding the image for the header manually.
//Step 1: Add the Image file
strImgPath is refer the directory Info..
Image imgLogo = Image.GetInstance(strImgPath.ToString()+"\\abcdur compe.Jpg");
imgLogo.Alignment = Image.ALIGN_CENTER;
imgLogo.ScalePercent(50f);
// Step 2:
Add this ImgLogo to the PdfPTable by use of this
PdfPCell pdfcellImage = new PdfPCell(imgLogo, true);
pdfcellImage.FixedHeight = 40f;
pdfcellImage.HorizontalAlignment = Element.ALIGN_CENTER;
pdfcellImage.VerticalAlignment = Element.ALIGN_CENTER;
pdfcellImage.Border = Rectangle.NO_BORDER;
pdfcellImage.Border = Rectangle.NO_BORDER;
pdftblImage.AddCell(pdfcellImage);
// Step 3:
Create Chunck to add Text for address or others
fntBoldComHd is a Base Font Library Object
Chunk chnCompany = new Chunk("Your CompanyName\nAddress", fntBoldComHd);
//Step 4:
Create Phrase For add the Chunks and PdfPTables
Phrase phHeader = new Phrase();
phHeader.Add(pdftblImage);
phHeader.Add(chnCompany);
// Step 5:
Assign the Phrase to PDF Header
HeaderFooter header = new HeaderFooter(phHeader, false);
header.Border = Rectangle.NO_BORDER;
header.Alignment = Element.ALIGN_CENTER;
docPDF.Header = header;
I am using one hacky way of workaround but it will create the border.Use this method.
private void CreateBorder(PdfContentByte cb, PdfWriter writer, Document doc)
{
iTextSharp.text.Rectangle r = doc.PageSize;
float left = r.Left + 30;
float right = r.Right - 30;
float top = r.Top - 30;
float bottom = r.Bottom + 30;
float width = right - left;
float height = top - bottom;
PdfPTable tab = new PdfPTable(1);
tab.TotalWidth = width;
tab.LockedWidth = true;
PdfPCell t = new PdfPCell(new Phrase(String.Empty));
t.BackgroundColor = new BaseColor(250, 235, 215);
t.FixedHeight = height;
t.BorderWidth = 3;
tab.AddCell(t);
Paragraph pa = new Paragraph();
pa.Add(tab);
float h = tab.TotalHeight;
PdfTemplate temp = cb.CreateTemplate(tab.TotalWidth, h);
tab.WriteSelectedRows(0, -1, 0.0F, h, temp);
iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(temp);
img.SetAbsolutePosition(30, 30);
cb.AddImage(img);
}
If u want one more section for header create table width two rows.I hope this helps.
Are you referring to the document margins? If yes, use the Document object's ctor to specify them:
public Document(Rectangle pageSize, float marginLeft, float marginRight, float marginTop, float marginBottom);

print an icard in pdf using itextsharp

I want to create a PDF file with Icard showing in it.
Following is the code:
iTextSharp.text.Font custFont = new iTextSharp.text.Font() { Size=6f};
int borderSize = 1;
Document IcardDoc = new Document(PageSize.HALFLETTER);
PdfWriter.GetInstance(IcardDoc, Response.OutputStream);
IcardDoc.Open();
PdfPTable icardTable = new PdfPTable(2);
iTextSharp.text.Image logoImage = iTextSharp.text.Image.GetInstance(Server.MapPath("~/images/logo.jpg"));
logoImage.WidthPercentage = 15f;
PdfPCell cell = new PdfPCell(logoImage, false);
cell.PaddingLeft = 10f;
cell.PaddingTop = 10f;
cell.PaddingBottom = 10f;
cell.PaddingRight = 10f;
cell.Colspan = 2;
cell.Border = 0;
cell.HorizontalAlignment = 1;
icardTable.AddCell(cell);
icardTable.AddCell(new PdfPCell(new Phrase("Name:", custFont)) { Border = borderSize });
icardTable.AddCell(new PdfPCell(new Phrase(student.firstname + " " + student.lastname, custFont)) { Border = borderSize });
The print document size will be 8.5 cm in height and 5.4 cm in width.
So need to fit it that way, is there any solution to this because the above code is not fitting the table on page and in proper size?
Any other format will also do like word etc.
figured out the solution :
Document IcardDoc = new Document(new Retangele(200f, 315f),35f,35f,0f,0f);
and adjust the width of the table accordingly:
PdfPTable icardTable = new PdfPTable(2);
icardTable.WidthPercentage = 140f;
to fit table exactly on page, if decrease rectangle width then increase table WidthPercentage and vice versa.
You also need to care of left and right margins defined as 35f in Document class constructor
This worked for me.
var pgSize = new iTextSharp.text.Rectangle(1042, 651);
var doc = new iTextSharp.text.Document(pgSize, 0, 0, 0, 0);

iTextsharp landscape document

I am trying to create Landscape PDF using iTextSharp but It is still showing portrait. I am using following code with rotate:
Document document = new Document(PageSize.A4, 0, 0, 150, 20);
FileStream msReport = new FileStream(Server.MapPath("~/PDFS/") + "Sample1.pdf", FileMode.Create);
try
{
// creation of the different writers
PdfWriter writer = PdfWriter.GetInstance(document, msReport);
document.Open();
PdfPTable PdfTable = new PdfPTable(1);
PdfTable.SpacingBefore = 30f;
PdfPCell PdfPCell = null;
Font fontCategoryheader = new Font(Font.HELVETICA, 10f, Font.BOLD, Color.BLACK);
for (int i = 0; i < 20; i++)
{
PdfPCell = new PdfPCell(new Phrase(new Chunk("Sales Manager: ", fontCategoryheader)));
PdfPCell.BorderWidth = 0;
PdfPCell.HorizontalAlignment = Element.ALIGN_LEFT;
if (i % 2 == 0)
PdfPCell.BackgroundColor = Color.LIGHT_GRAY;
PdfPCell.PaddingBottom = 5f;
PdfPCell.PaddingLeft = 2f;
PdfPCell.PaddingTop = 4f;
PdfPCell.PaddingRight = 4f;
PdfTable.AddCell(PdfPCell);
}
document.Add(PdfTable);
document.NewPage();
}
catch (Exception ex)
{
Console.Error.WriteLine(ex.Message);
}
finally
{
// we close the document
document.Close();
}
Please suggest solution.
Thanks.
Try this
Document Doc = new Document(new Rectangle(288f, 144f), 10, 10, 10, 10);
Doc.SetPageSize(iTextSharp.text.PageSize.A4.Rotate());
you might also need this to expand a table to max width.
var _pdf_table = new PdfPTable(2); // table with two columns
PdfPCell hc = new PdfPCell();
_pdf_table.WidthPercentage = 100; //table width to 100per
_pdf_table.SetTotalWidth(new float[] { 25, iTextSharp.text.PageSize.A4.Rotate().Width - 25 });// width of each column
You must make sure that when setting the page size you do it before a call to Doc.Open();
Regards.
No need to initialize the Document and reset the page size...
Document doc = new Document(iTextSharp.text.PageSize.A4.Rotate(), 10, 10, 10, 10);
...will do the trick.
(4.1.6.0)

Categories