why courier font not working in iText PDF document? - c#

Using the following code to create a PDF document in C# using iText 5. The text does not render in the courier font. Why not?
private void SimpleFontDoc(string pdfDocPath)
{
Document doc = new Document(PageSize.LETTER, 10, 10, 42, 30);
var fs = new FileStream(pdfDocPath, FileMode.Create);
PdfWriter writer = PdfWriter.GetInstance(doc, fs);
doc.Open();
string[] lines = new string[]
{
"First text line",
"Second text line"
};
var font = FontFactory.GetFont("courier", 12.0f, BaseColor.BLACK);
foreach (var line in lines)
{
var para = new iTextSharp.text.Paragraph(line);
para.Font = font;
doc.Add(para);
}
doc.Close();
}

In iText5 you have to specify the font before adding text to the Paragraph element (or alternatively pass it to the constructor).
Change
var para = new iTextSharp.text.Paragraph(line);
para.Font = font;
into
var para = new iTextSharp.text.Paragraph(line, font);

Related

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();

Error when using font Times New Roman bold in pdfsharp

I have used pdfSharp to insert text into PDF file but when I use font Times New Roman bold, there are some problems.
Here is my code :
using PdfSharp.Pdf;
using PdfSharp.Drawing;
PdfSharp.Pdf.PdfDocument pdf = new PdfSharp.Pdf.PdfDocument();
pdf.Info.Title = filePrint;
PdfSharp.Pdf.PdfPage pdfPage = pdf.AddPage();
pdfPage.Size = PdfSharp.PageSize.A4;
using (XGraphics graph = XGraphics.FromPdfPage(pdfPage))
{
XPdfFontOptions options = new XPdfFontOptions(PdfFontEncoding.Unicode, PdfFontEmbedding.Always);
XFont fontBold = new XFont("Times New Roman", 10, XFontStyle.Bold, options);
graph.DrawString("Đây là đoạn text bold", fontBold, XBrushes.Black, new XRect(75.6, 56, 30, 30), XStringFormats.TopLeft);
}
Then my result is like this:
Please help me to find solution for this error.
You can use additionnaly MigraDoc.
Following this article :
Can you try this :
using MigraDoc.DocumentObjectModel;
using MigraDoc.Rendering;
using PdfSharp.Drawing;
using PdfSharp.Pdf;
using (var document = new PdfDocument())
{
PdfPage page = document.AddPage();
XGraphics graph = XGraphics.FromPdfPage(page);
graph.MUH = PdfFontEncoding.Unicode;
graph.MFEH = PdfFontEmbedding.Always;
// You always need a MigraDoc document for rendering.
Document doc = new Document();
Section section = doc.AddSection();
Font font = new Font("Times New Roman", 12);
foreach (var line in textFileLines)
{
Paragraph paragraph = section.AddParagraph();
paragraph.AddFormattedText(line, font);
}
//save pdf document
PdfDocumentRenderer renderer = new PdfDocumentRenderer();
renderer.Document = doc;
renderer.RenderDocument();
renderer.Save(output);
}

Html to pdf Unicode chars not being displayed in pdfptable

I am writing a pdf file from html markup. In my code snippet the pdf is being successfully generated and the unicode characters are being also being rendered on the table.
Here is my code snippet:
void GeneratePdfFromHtml()
{
const string outputFilename = #"c:\report.pdf";
const string inputFilename = #"C:\report.html";
using (var input = new FileStream(inputFilename, FileMode.Open))
using (var output = new FileStream(outputFilename, FileMode.Create))
{
CreatePdf(input, output);
}
}
and this method creates pdf with unicode support:
void CreatePdf(Stream htmlInput, Stream pdfOutput)
{
using (var document = new Document(PageSize.A4, 30, 30, 30, 30))
{
var writer = PdfWriter.GetInstance(document, pdfOutput);
var worker = XMLWorkerHelper.GetInstance();
document.Open();
worker.ParseXHtml(writer, document, htmlInput, null, Encoding.Unicode, new UnicodeFontFactory());
document.Close();
}
}
This is a helper class to provide required fonts:
public class UnicodeFontFactory : FontFactoryImp
{
private static readonly string FontPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
"ARIALUNI.ttf");
private readonly BaseFont _baseFont;
public UnicodeFontFactory()
{
_baseFont = BaseFont.CreateFont(FontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
}
public override iTextSharp.text.Font GetFont(string fontname, string encoding, bool embedded, float size, int style, BaseColor color,
bool cached)
{
return new iTextSharp.text.Font(_baseFont, size, style, color);
}
}
Problem this draws the resultant contents on Pdf document page but I want this to be drawn in a pdfptable cell.
What I have tried to achieve this:
void CreatePdf(string htmltext)
{
using (var document = new Document(PageSize.A4, 30, 30, 30, 30))
{
document.Open();
PdfPTable table = new PdfPTable(1);
PdfPCell cell = new PdfPCell();
List<IElement> elementsIzv = XMLWorkerHelper.ParseToElementList(htmltext, null);
foreach (IElement e in elementsIzv)
{
cell.AddElement(e);
}
table.AddCell(cell);
document.Add(table);
document.Close();
}
}
This snippet truncates the Special Characters. Please direct me in the right way, Any replacement to itextsharp is also acceptable.

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?

ItextSharp doesn't display Japanese font

iTextSharp doesn't display Japanese font. I found a solution but when I compile, I get an error saying:
Font 'STSong-Light' with 'UniGB-UCS2-H' is not recognized.
Here's my source code:
BaseFont.AddToResourceSearch(serverPath + "\\lib\\iTextAsian.dll");
BaseFont.AddToResourceSearch(serverPath + "\\lib\\iTextAsianCmaps.dll");
BaseFont font = BaseFont.CreateFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
using (Document document = new Document())
{
using (PdfSmartCopy copy = new PdfSmartCopy(
document, new FileStream(directoryOutPdf + nameOutPdf, FileMode.Create))
)
{
document.Open();
// generate one page per statement
for (int i = 0; i < countBlank.Count; i++)
{
// replace this with your PDF form template
PdfReader reader = new PdfReader(pdfTemplatePath + #"\EmptyTemplateBankBlank_2012.pdf");
using (var ms = new MemoryStream())
{
using (PdfStamper stamper = new PdfStamper(reader, ms))
{
AcroFields form = stamper.AcroFields;
form.SetFieldProperty("Info", "textfont", font, null);
form.SetField("Info", "_源泉徴収票");
stamper.FormFlattening = true;
}
reader = new PdfReader(ms.ToArray());
copy.AddPage(copy.GetImportedPage(reader, 1));
}
}
}
}
I think it's because I didn't install the STSong-Light font. Unfortunately I could not find STSong-Light and, therefore, had to set Stsong font, but it still does not work.
String fontPath = Path.Combine(serverPath + "\\Fonts", "STSONG.ttf");
BaseFont baseFont = BaseFont.CreateFont(fontPath, "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
Font font = new Font(baseFont, 12, Font.NORMAL);
Set the SubstitutionFont after creating the PdfStamper:
stamper.AcroFields.AddSubstitutionFont(myFont.BaseFont);

Categories

Resources