Multiple images and texts on same line using iTextSharp - c#

I am trying to create a PDF file on the fly using some backend data and at the bottom of the file I need to include 2 images and a text: a signature image on the left, company logo in the middle and date (underlined with the word "Date" below the line).
I have searched and managed to do two: image on the left and date on the right but now I am stuck trying to get another image in between!
This is what I currently have (assuming I have already read user's name and test date from DB):
using (MemoryStream ms = new MemoryStream())
{
Document doc = new Document(PageSize.LETTER.Rotate());
doc.Open();
// Set path to PDF file and images used in the file
string sPath = Server.MapPath("PDF");
string sImagePath = Server.MapPath("assets/Images");
// Set PDF file name
string sFileName = "SomeFileNameGenerated" + ".PDF";
// Open document
PdfWriter myPDFWriter = PdfWriter.GetInstance(doc, ms);
doc.Open();
// Set some font styles
BaseFont bfTimes = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false);
Font fntDate = new Font(Font.FontFamily.TIMES_ROMAN, 12f, Font.NORMAL | Font.UNDERLINE, BaseColor.BLACK);
Font fntUserName = new Font(Font.FontFamily.TIMES_ROMAN, 24f, Font.BOLD | Font.UNDERLINE, BaseColor.BLACK);
// Add header image
iTextSharp.text.Image imgHeader = iTextSharp.text.Image.GetInstance(sImagePath + "/headerImage.png");
doc.Add(imgHeader);
iTextSharp.text.Image imgSignature = iTextSharp.text.Image.GetInstance(sImagePath + "/Signature.png");
// Add user's name, underlined, in the center
Paragraph pUserName = new Paragraph(sUserName, fntUserName);
pUserName.Alignment = Element.ALIGN_CENTER;
doc.Add(pUserName);
// Here I am trying to add two images and one date text;
// below I have added one image and one text; need to have another image in between
Paragraph para = new Paragraph();
Phrase ph1 = new Phrase();
Chunk glue = new Chunk(new iTextSharp.text.pdf.draw.VerticalPositionMark());
Paragraph main = new Paragraph();
ph1.Add(new Chunk(imgSignature, 0, 0, true)); // Here I add signature image as a chunk into Phrase.
ph1.Add(glue); // Here I add special chunk to the same phrase.
ph1.Add(new Chunk(sTestDate, fntDate)); // Here I add date as a chunk into same phrase.
main.Add(ph1);
para.Add(main);
doc.Add(para);
doc.Close();
}

Related

Why is my document.Add(paragraph) not working (wpf, iText)?

I am trying to create a pdf using iText in WPF. But I am not able to add any paragraphs to my document.
Here's my code:
string destination = "po.pdf";
var fos = File.Create(destination);
PdfWriter writer = new PdfWriter(fos);
PdfDocument pdf = new PdfDocument(writer);
Document document = new Document(pdf, PageSize.A4.Rotate());
Paragraph p1 = new Paragraph();
p1.Inlines.Add(new TextBlock()
{
Text = "hello"
});
document.Add(p1);
document.Close();
}
Here, in the second last line (document.Add(p1)), I get a red underline under 'p1'.
The error says --- Cannot convert from 'System.Windows.Documents.Paragraph' to 'iText.Layout.Element.AreaBreak'.
Thank you in advance.

Itextsharp chinese character not shown in PDF

I need so help with my coding. I am trying to convert a HTML with Chinese Character to PDF. I manage to Convert but my chinese characters has disappear
This is my HTML file which i convert to string and i have set font with Arial Unicode MS in the td
string HTMLTemplate = "<table border=0 cellspacing='0' cellpadding='3'><tr><td style='width:100%;font: 10px/1.5em Verdana, Arial Unicode MS, Helvetica, sans-serif;'>GIGI无合约 F&B‎</td></tr></table>"
This is my code
XMLWorkerFontProvider fontProvider = new XMLWorkerFontProvider(XMLWorkerFontProvider.DONTLOOKFORFONTS);
fontProvider.Register("C:\\fonts\\ARIALUNI.TTF");
CssAppliers cssAppliers = new CssAppliersImpl(fontProvider);
iTextSharp.text.Document doc = new iTextSharp.text.Document(iTextSharp.text.PageSize.LETTER, 7, 7, 7, 7);
iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(doc, new FileStream(FilePath, FileMode.Create));
iTextSharp.tool.xml.pipeline.html.HtmlPipelineContext htmlContext = new iTextSharp.tool.xml.pipeline.html.HtmlPipelineContext(cssAppliers);
htmlContext.SetTagFactory(iTextSharp.tool.xml.html.Tags.GetHtmlTagProcessorFactory());
//create a cssresolver to apply css
iTextSharp.tool.xml.pipeline.css.ICSSResolver cssResolver = iTextSharp.tool.xml.XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false);
//Create and attach pipline, without pipline parser will not work on css
iTextSharp.tool.xml.IPipeline pipeline = new iTextSharp.tool.xml.pipeline.css.CssResolverPipeline(cssResolver, new iTextSharp.tool.xml.pipeline.html.HtmlPipeline(htmlContext, new iTextSharp.tool.xml.pipeline.end.PdfWriterPipeline(doc, writer)));
//Create XMLWorker and attach a parser to it
iTextSharp.tool.xml.XMLWorker worker = new iTextSharp.tool.xml.XMLWorker(pipeline, true);
iTextSharp.tool.xml.parser.XMLParser xmlParser = new iTextSharp.tool.xml.parser.XMLParser(worker);
//All is well open documnet and start writing.
doc.Open();
xmlParser.Parse(new StringReader(AP_TEMPLATE_HTML));
doc.NewPage();
doc.Close();

getting text from a pdf document itextsharp

i tried using iTextSharp to get the text from a pdf document,
it works great if the pdf file is with english text(latin chars).
If i try to get the text from a pdf doc with cyrillic characters the output is just question marks. Are there some settings to be made, or cyrillic isnt supported?
this is the code for creating the pdf:
string testText = "зззi";
string tmpFile = #"C:\items\test.pdf";
string myFont = #"C:\windows\fonts\verdana.ttf";
iTextSharp.text.Rectangle pgeSize = new iTextSharp.text.Rectangle(595, 792);
iTextSharp.text.Document doc = new iTextSharp.text.Document(pgeSize, 10, 10, 10, 10);
iTextSharp.text.pdf.PdfWriter wrtr;
wrtr = iTextSharp.text.pdf.PdfWriter.GetInstance(doc,
new System.IO.FileStream(tmpFile, System.IO.FileMode.Create));
doc.Open();
doc.NewPage();
iTextSharp.text.pdf.BaseFont bfR;
bfR = BaseFont.CreateFont(myFont, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
iTextSharp.text.BaseColor clrBlack =
new iTextSharp.text.BaseColor(0, 0, 0);
iTextSharp.text.Font fntHead =
new iTextSharp.text.Font(bfR, 34, iTextSharp.text.Font.NORMAL, clrBlack);
iTextSharp.text.Paragraph pgr =
new iTextSharp.text.Paragraph(testText, fntHead);
doc.Add(pgr);
doc.Close();
this is the code for retrieving the text:
PdfReader reader1
= new PdfReader("c:/items/test.pdf");
Console.WriteLine(PdfTextExtractor.GetTextFromPage(reader1, 1, new SimpleTextExtractionStrategy()));
Console.ReadLine();
the output is: ???i
EDIT 2
i managed to read text from the pdf i created, but still cant get the text from a random pdf. How can i check if that pdf provides the required info for text extraction?

Placing Images and Text in Specific (Absolute) Locations Using iTextSharp

I am generating a PDF using iTextSharp and there is dynamic content in the middle of the page which is pushing the bottom part of my PdfPTable down too far. Sometimes even off the bottom of the page onto another page.
Would it be possible to position the bottom PdfPTable in a way that it would not get pushed down when the table above it needs more vertical space?
Here is my solution.
Views\Home\Index.cshtml:
<h2>Create PDF</h2>
#Html.ActionLink("Create the PDF", "CreatePDF", "Home")
</div>
HomeController.cs:
public ActionResult Index()
{
return View();
}
public FileStreamResult CreatePDF()
{
Stream fileStream = GeneratePDF();
HttpContext.Response.AddHeader("content-disposition", "inline; filename=MyPDF.pdf");
var fileStreamResult = new FileStreamResult(fileStream, "application/pdf");
return fileStreamResult;
}
private Stream GeneratePDF()
{
var rect = new Rectangle(288f, 144f);
var document = new Document(rect, 10, 10, 10, 10);
document.SetPageSize(PageSize.LETTER.Rotate());
MemoryStream memoryStream = new MemoryStream();
PdfWriter pdfWriter = PdfWriter.GetInstance(document, memoryStream);
document.Open();
////////////////////////
//Place Image in a Specific (Absolute) Location
////////////////////////
Image myImage = Image.GetInstance(Server.MapPath("../Content/BI_logo_0709.png"));
myImage.SetAbsolutePosition(45, 45);
//[dpi of page]/[dpi of image]*100=[scale percent]
//72 / 200 * 100 = 36%
//myImage.ScalePercent(36f);
myImage.ScalePercent(36f);
document.Add(myImage);
////////////////////////
//Place Text in a Specific (Absolute) Location
////////////////////////
//Create a table to hold everything
PdfPTable myTable = new PdfPTable(1);
myTable.TotalWidth = 200f;
myTable.LockedWidth = true;
//Create a paragraph with the text to be placed
BaseFont bfArialNarrow = BaseFont.CreateFont(Server.MapPath("../Content/ARIALN.ttf"), BaseFont.CP1252, BaseFont.EMBEDDED);
var basicSmaller = new Font(bfArialNarrow, 10);
var myString = "Hello World!" +
Environment.NewLine +
"Here is more text." +
Environment.NewLine +
"Have fun programming!";
var myParagraph = new Paragraph(myString, basicSmaller);
//Create a cell to hold the text aka paragraph
PdfPCell myCell = new PdfPCell(myParagraph);
myCell.Border = 0;
//Add the cell to the table
myTable.AddCell(myCell);
//Add the table to the document in a specific (absolute) location
myTable.WriteSelectedRows(0, -1, 550, 80, pdfWriter.DirectContent);
pdfWriter.CloseStream = false;
document.Close();
memoryStream.Position = 0;
return memoryStream;
}

arabic encoding in itextsharp

When I'm trying this code to create a PDF in Arabic using C#, the generated PDF file contains discrete characters. Any help so I can't get continuous characters?
//Create our document object
Document Doc = new Document(PageSize.LETTER);
//Create our file stream
using (FileStream fs = new FileStream(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Test.pdf"), FileMode.Create, FileAccess.Write, FileShare.Read))
{
//Bind PDF writer to document and stream
PdfWriter writer = PdfWriter.GetInstance(Doc, fs);
//Open document for writing
Doc.Open();
//Add a page
Doc.NewPage();
//Full path to the Unicode Arial file
string ARIALUNI_TFF = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "arabtype.TTF");
//Create a base font object making sure to specify IDENTITY-H
BaseFont bf = BaseFont.CreateFont(ARIALUNI_TFF, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
//Create a specific font object
iTextSharp.text.Font f = new iTextSharp.text.Font(bf, 12, iTextSharp.text.Font.NORMAL);
//Write some text, the last character is 0x0278 - LATIN SMALL LETTER PHI
Doc.Add(new Phrase("This is a ميسو ɸ", f));
//Write some more text, the last character is 0x0682 - ARABIC LETTER HAH WITH TWO DOTS VERTICAL ABOVE
Doc.Add(new Phrase("Hello\u0682", f));
//Close the PDF
Doc.Close();
}
Right-to-left writing and Arabic ligatures are only supported in ColumnText and PdfPTable!
Take a look at the following examples:
http://itextpdf.com/examples/iia.php?id=205 with result: say_peace.pdf
http://itextpdf.com/examples/iia.php?id=215 with result: peace.pdf
Read the book from which these examples are taken to find out why not all words are rendered correctly in peace.pdf
Search http://tinyurl.com/itextsharpIIA2C11 for the corresponding C# version of these examples.
In any case, you need a font that knows how to display Arabic glyphs:
BaseFont bf = BaseFont.CreateFont(ARIALUNI_TFF, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
Font f = new Font(bf, 12);
You can now add Arabic text, for instance in a table:
PdfPCell cell = new PdfPCell();
cell.AddElement(new Phrase("Hello\u0682", f));
cell.RunDirection = PdfWriter.RUN_DIRECTION_RTL;

Categories

Resources