I have to add (register, embed) font to a PDF programmatically.
I tried with a lot of utilities like ghostscript or itextsharp but i did not manage to solve the problem.
For example in a situation like this one:
I would like to add Courier-Bold and get this situation:
I just created a project using iTextSharp v5.5.9 via NuGet and used the following code:
const string PdfLocation = #"C:\fakepath\output.pdf";
static void Main(string[] args)
{
using (var pdfDoc = new Document())
using (var fs = new FileStream(PdfLocation, FileMode.OpenOrCreate))
using (var writer = PdfWriter.GetInstance(pdfDoc, fs))
{
pdfDoc.Open();
var font = FontFactory.GetFont(FontFactory.COURIER_BOLD);
// Doesn't use font
var paragraph = new Paragraph("LINE 1");
paragraph.Font = font;
pdfDoc.Add(paragraph);
// Doesn't use font
var paragraph2 = new Paragraph();
paragraph2.Add("LINE 2");
paragraph2.Font = font;
pdfDoc.Add(paragraph2);
// Does use font
var paragraph3 = new Paragraph();
paragraph3.Font = font;
paragraph3.Add("LINE 3"); // This must be done after setting the font
pdfDoc.Add(paragraph3);
var cb = writer.DirectContent;
pdfDoc.Close();
}
}
I discovered that you need to set the font first before you write the text. The following code outputs the PDF with the following properties. I didn't get the TrueType requirement out of this, but perhaps this will set you in the right direction.
Where I'm using paragraph and paragraph2 will use the default font which was Helvetica for me because I'm setting the font after I'm setting the text. Order does matter!
The documentation for this certainly needs to be expanded upon...
Related
I want to change existing font style regular to bold, increase font size. Like if font style is regular I want to change it to bold. If font size 10 then i want to increase or decrease one size it(10->11 or 10->9)
After searching on this topic I found this code but this gives only the information of font and it doesn't change style and size
string OutputFile = "font.pdf";
//PdfReader pdfReader = new PdfReader(strFile);
PdfReader pdfReader = new PdfReader(mStream.ToArray());
//Get first page,Generally we get font information on first page,however we can loop throw pages e.g for(int i=0;i<=pdfReader.NumberOfPages;i++)
PdfDictionary cpage = pdfReader.GetPageN(1);
if (cpage == null)
return;
PdfDictionary dictFonts = cpage.GetAsDict(PdfName.RESOURCES).GetAsDict(PdfName.FONT);
if (dictFonts != null)
{
foreach (var font in dictFonts)
{
var dictFontInfo = dictFonts.GetAsDict(font.Key);
if (dictFontInfo != null)
{
//Get the font name-optional code
var baseFont = dictFontInfo.Get(PdfName.BASEFONT);
string strFontName = System.Text.Encoding.ASCII.GetString(baseFont.GetBytes(), 0, baseFont.Length);
//var bf = BaseFont.CreateFont((PRIndirectReference)baseFont);
//iTextSharp.text.Font exFont =new iTextSharp.text.Font(bf,20f);
//Remove the current font
//dictFontInfo.Remove(PdfName.BASEFONT);
//Set new font eg. Braille, Areal etc
//dictFontInfo.Put(PdfName.BASEFONT, new PdfString("Braille"));
}
}
}
//Now create a new document with updated font
using (FileStream FS = new FileStream(OutputFile, FileMode.Create, FileAccess.Write, FileShare.None))
{
using (Document Doc = new Document())
{
using (PdfCopy writer = new PdfCopy(Doc, FS))
{
Doc.Open();
for (int j = 1; j <= pdfReader.NumberOfPages; j++)
{
writer.AddPage(writer.GetImportedPage(pdfReader, j));
}
Doc.Close();
}
}
}
pdfReader.Close();
i want also to change some font like Arial to some other font.
Changing the font of an existing PDF can not be done in a meaningful, generic way, without risk of messing up the layout.
To illustrate, assume you have the following text.
I'm using | to indicate a page-boundary.
Lorem Ipsum Dolor |
Sit Amet Consectetur|
Nunc |
If I make this text larger, or make it bold, or even italic, it is likely to take up more space. That means the word 'Consectetur' will no longer fit on the line.
PDF (unlike a Word document) does not automatically re-flow its content. The content would simply appear to go over the page boundary (and depending on the viewer you are using it might vanish).
The real problem is that the PDF format does not have the same information as the word format.
where are word-boundaries located?
where are paragraph boundaries?
(what language is this text being written in?)
All of these are important when performing layout for a document. And none of these are naturally present in a PDF document.
I'm trying to create a PDF from HTML, and am using iTextSharp for that. From my reading, the license that covers the newer versions of iTextSharp would require me to make the source code available. We can't do that, so we're using version 4, which is under the LGPL.
I'm trying to get a footer to appear along with the HTML, but it's not working for some reason. I've tried removing the HTML and just using text. Just putting a chunk in the footer. Multiple pages vs single pages. Hopefully I'm just missing something easy, but from the examples I've seen it should be super easy.
using (MemoryStream ms = new MemoryStream())
{
Document doc = new Document(PageSize.LETTER, 35,35,35,70);
var font = FontFactory.GetFont("arial", 8f);
font.Color = Color.BLACK;
var chunk = new Chunk("Footer", font);
var phrase = new Phrase(chunk);
var footer = new HeaderFooter(phrase, true);
footer.Alignment = 1;
footer.Border = Rectangle.NO_BORDER;
doc.Footer = footer;
//doc.Footer = new HeaderFooter(new Phrase("Footer"),false);
var writer = PdfWriter.GetInstance(doc, ms);
var htmlWorker = new HTMLWorker(doc);
using (var sr = new StringReader(html))
{
doc.Open();
doc.Add(new Chunk("Text"));
//htmlWorker.Parse(sr);
doc.Close();
}
return ms.ToArray();
}
Watch your HeaderFooter ctor. The signature your are using might lead to setting the header text only.
Anyway maybe use the PdfWriter.PageEvent and some class deriving from PdfPageEventHelper to implement header and footer (instead of HeaderFooter())
When I export ARABIC data into pdf.Microsoft adobereader showing error.Adobe reader could not open file because it is either not a supported file.My code is following asp.net c#.Guide me
protected void btnExport_Click(object sender, EventArgs e)
{
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=TestPage.pdf");
Document doc = new Document(PageSize.LETTER);
doc.Open();
//Sample HTML
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append(#"<p>This is a test: <strong>مسندم</strong></p>");
//Path to our font
string arialuniTff = Server.MapPath("~/tradbdo.TTF");
//Register the font with iTextSharp
iTextSharp.text.FontFactory.Register(arialuniTff);
//Create a new stylesheet
iTextSharp.text.html.simpleparser.StyleSheet ST = new iTextSharp.text.html.simpleparser.StyleSheet();
//Set the default body font to our registered font's internal name
ST.LoadTagStyle(HtmlTags.BODY, HtmlTags.FACE, "Traditional Arabic Bold");
//Set the default encoding to support Unicode characters
ST.LoadTagStyle(HtmlTags.BODY, HtmlTags.ENCODING, BaseFont.IDENTITY_H);
//Parse our HTML using the stylesheet created above
List<IElement> list = HTMLWorker.ParseToList(new StringReader(stringBuilder.ToString()), ST);
//Loop through each element, don't bother wrapping in P tags
foreach (var element in list)
{
doc.Add(element);
}
doc.Close();
Response.Write(doc);
Response.End();
}
I found the following article which shows how to correctly export and display Arabic content via the iTextSharp library: http://geekswithblogs.net/JaydPage/archive/2011/11/02/using-itextsharp-to-correctly-display-hebrew--arabic-text-right.aspx.
Here is the code sample that you can try:
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.Text.RegularExpressions;
using System.IO;
using System.Diagnostics;
public void WriteDocument()
{
//Declare a itextSharp document
Document document = new Document(PageSize.A4);
//Create our file stream and bind the writer to the document and the stream
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(#"C:\Test.Pdf", FileMode.Create));
//Open the document for writing
document.Open();
//Add a new page
document.NewPage();
//Reference a Unicode font to be sure that the symbols are present.
BaseFont bfArialUniCode = BaseFont.CreateFont(#"C:\ARIALUNI.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
//Create a font from the base font
Font font = new Font(bfArialUniCode, 12);
//Use a table so that we can set the text direction
PdfPTable table = new PdfPTable(1);
//Ensure that wrapping is on, otherwise Right to Left text will not display
table.DefaultCell.NoWrap = false;
//Create a regex expression to detect hebrew or arabic code points
const string regex_match_arabic_hebrew = #"[\u0600-\u06FF,\u0590-\u05FF]+";
if (Regex.IsMatch("مسندم", regex_match_arabic_hebrew, RegexOptions.IgnoreCase))
{
table.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
}
//Create a cell and add text to it
PdfPCell text = new PdfPCell(new Phrase("مسندم", font));
//Ensure that wrapping is on, otherwise Right to Left text will not display
text.NoWrap = false;
//Add the cell to the table
table.AddCell(text);
//Add the table to the document
document.Add(table);
//Close the document
document.Close();
//Launch the document if you have a file association set for PDF's
Process AcrobatReader = new Process();
AcrobatReader.StartInfo.FileName = #"C:\Test.Pdf";
AcrobatReader.Start();
}
The iTextSharp.text.Document is a class used to help bridge human concepts like Paragraph and Margin into PDF concepts. The bridge part is important. It is not a PDF file in any way so it should never be treated as a PDF. Doing so would be like treating System.Drawing.Graphics as if it were an image. This leads to one of your problems on the second to last line of code that tries to treat the Document as if it were a PDF by sending it directly to the output stream:
//This won't work
Response.Write(doc);
You will find many, many tutorials out there that do this and they are all wrong. Fortunately (or unfortunately), PDF is forgiving and allows junk data at the end so only a handful of PDF fail and people assume there was some other problem.
Your other problem is that you are missing a PdfWriter. If Document is the bridge, PdfWriter is the actual construction worker that puts that PDF together. It, however, is also not a PDF. Instead, it needs to be bound to a stream like a file, in-memory or the HttpResponse.OutputStream.
Below is some code that shows this off. I very strongly recommend separating your PDF logic from your ASPX logic. Do all of you PDF stuff first and get an actual "something" that represents a PDF, then do something with it.
At the beginning we declare a byte array that we'll fill in later. Next we create a System.IO.MemoryStream that will be used to write the PDF to. After creating the Document we then create a PdfWriter that's bound to the Document and our stream. Your internal code is the same and although I didn't test it it appears correct. Right before we're done with our MemoryStream we grab the active bytes into our byte array. Lastly we use the BinaryWrite() method to send our raw binary PDF to the requesting client.
//At the end of this bytes will hold a byte array representing an actual PDF file
Byte[] bytes;
//Create a simple in-memory stream
using (var ms = new MemoryStream()){
using (var doc = new Document()) {
//Create a new PdfWriter bound to our document and the stream
using (var writer = PdfWriter.GetInstance(doc, ms)) {
doc.Open();
//This is unchanged from the OP's code
//Sample HTML
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append(#"<p>This is a test: <strong>مسندم</strong></p>");
//Path to our font
string arialuniTff = Server.MapPath("~/tradbdo.TTF");
//Register the font with iTextSharp
iTextSharp.text.FontFactory.Register(arialuniTff);
//Create a new stylesheet
iTextSharp.text.html.simpleparser.StyleSheet ST = new iTextSharp.text.html.simpleparser.StyleSheet();
//Set the default body font to our registered font's internal name
ST.LoadTagStyle(HtmlTags.BODY, HtmlTags.FACE, "Traditional Arabic Bold");
//Set the default encoding to support Unicode characters
ST.LoadTagStyle(HtmlTags.BODY, HtmlTags.ENCODING, BaseFont.IDENTITY_H);
//Parse our HTML using the stylesheet created above
List<IElement> list = HTMLWorker.ParseToList(new StringReader(stringBuilder.ToString()), ST);
//Loop through each element, don't bother wrapping in P tags
foreach (var element in list) {
doc.Add(element);
}
doc.Close();
}
}
//Right before closing the MemoryStream grab all of the active bytes
bytes = ms.ToArray();
}
//We now have a valid PDF and can do whatever we want with it
//In this case, use BinaryWrite to send it directly to the requesting client
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=TestPage.pdf");
Response.BinaryWrite(bytes);
Response.End();
I have pdf template ready with me.On which write values matching keys on pdf.Need to set different font and font size based on requireemnt Using itextsharp(pdfstamper).
But I want to set various diffent font like CourierNew,Arial and some other third party registered font.How do I use those different fonts using itextsharp.
Please refer following code snippet.
Following code snippet used to write values on pdf template
To set font call function SetPrintFont where different font and font size defined.
Please guide on the same
var pdfReader = new PdfReader(filebyte);
var pdfStamper = new PdfStamper(pdfReader, new FileStream(pdfname, FileMode.Create));
AcroFields pdfFormFields = pdfStamper.AcroFields;
foreach (DictionaryEntry de in pdfReader.AcroFields.Fields)
{
//set the field to bold
pdfFormFields.SetFieldProperty(de.Key.ToString(), "textfont", font.BaseFont, null);
Regex regex = new Regex(#"^\d$");
if (regex.IsMatch(de.Key.ToString()))
{
//set the text of the form field
pdfFormFields.SetField(de.Key.ToString(), response.ResponseValues.ToString());
}
else
{
pdfFormFields.SetField(de.Key.ToString(), response.ResponseValues.ToString());
}
}
pdfStamper.FormFlattening = false;
pdfStamper.Close();
}
You can get the list of registerred fonts like this:
ICollection<string> registeredFonts = iTextSharp.text.FontFactory.RegisteredFonts;
Anyway in iTextSharp you can use any font you want. If you don't find desired font you can download .ttf file from the internet and attach it:
BaseFont baseFont = BaseFont.CreateFont(fontFolderPath + "arial.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED)
Font font = iTextSharp.text.Font(baseFont, fontSize, iTextSharp.text.Font.BOLD);
BaseFont is a member of iTextSharp.text.pdf
we are creating pdf files in our C# application by passing TAMIL text(one of the indian language).So, I already installed AVVAIYAR.TTF(one of the tamil font) font for my tamil language font.But when i run the below mentioned pgm, the created pdf file does not contain any tamil font display.It shows empty lines instead of the tamil text...
C# Code:
Document document = new Document();
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(#"C:\pdfout.pdf", FileMode.Create));
document.Open();
PdfContentByte pcb = writer.DirectContent;
Font ft = new Font();
FontFactory.Register(#"C:\WINDOWS\Fonts\AVVAIYAR.TTF", "AVVAIYAR");
ft = FontFactory.GetFont("AVVAIYAR");
Paragraph pr1 = new Paragraph("இது முதல் பேரா", ft);
Paragraph pr2 = new Paragraph("This is a Sub Paragraph");
Paragraph pr3 = new Paragraph("This is the Second Paragraph");
document.Add(pr1);
document.Add(pr2);
document.Add(pr3);
document.Close();
my output pdf file is :
<blank line>
This is a Sub Paragraph
This is the Second Paragraph
And also i have to support some more indian languages to create the PDF files.
Can you please try the following code snippet?
string fontpath = Environment.GetEnvironmentVariable("SystemRoot") + "\\fonts\\AVVAIYAR.TTF";
BaseFont basefont = BaseFont.CreateFont(fontpath, BaseFont.IDENTITY_H, true);
Font AVVAIYARFont = new iTextSharp.text.Font(basefont, 24, iTextSharp.text.Font.NORMAL, iTextSharp.text.Color.BLUE); /*For test color blue is placed with some foramtting.*/
Paragraph pr1 = new Paragraph("இது முதல் பேரா", AVVAIYARFont);
This should work...
An out of the box thought, iText has not full support for all the indic languages at moment...See here they say that they dont have enough volunteers to support this.
I have put a reference to ARIALUNI.TTF.I tried like this,
string fontpath = Environment.GetEnvironmentVariable("SystemRoot") + "\\fonts\\ARIALUNI.TTF";
BaseFont basefont = BaseFont.CreateFont(fontpath, BaseFont.IDENTITY_H, true);
Font font = new iTextSharp.text.Font(basefont, 24, iTextSharp.text.Font.NORMAL, iTextSharp.text.Color.BLUE);
Paragraph pr1 = new Paragraph("இது முதல் பேரா", AVVAIYARFont);
So, now tamil font is displayed in the pdf file.But simple simple spelling mistake... so i am doing some read on that issue...
Procees 1:
step 1:Go to http://software.nhm.in/services/converter website
step2:paste this word படிவம்-டி ஊதியம் சீட்டு /விடுப்பு அட்டை
step3:1.change the first drop down to Unicode , 2.change the second drop down to TAB
step5:click the button converter
step6.text will be alligned.
step 7:main process start from hear
1.change the second drop down to TSCII and click on convert.(dont panic no changes would exists)
2.now change the first drop down to Unicode automatticaly the tamil text would change to "ÀÊÅõ-Ê °¾¢Âõ º£ðÎ /Å¢ÎôÒ «ð¨¼";
3.copy the content and place it in notepad.
Process 2:
1.First download TSC-Sri.ttf(http://www.eaglefonts.com/download.php?action=zip&image_id=129859)
2.save or move it in c:\Windows\fonts
3.finally Pate the below code in the c# program
string fontpath = Environment.GetEnvironmentVariable("SystemRoot") + "\\fonts\\TSC-Sri.ttf";
BaseFont basefont = BaseFont.CreateFont(fontpath, BaseFont.IDENTITY_H, true);
iTextSharp.text.Font font = new iTextSharp.text.Font(basefont, 24, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLUE);
Paragraph pr1 = new Paragraph("ÀÊÅõ-Ê °¾¢Âõ º£ðÎ /Å¢ÎôÒ «ð¨¼ ", font);
4.run the itextsharp pdf program output as excepted 100% working.
A viable alternative is Quest PDF.
using QuestPDF.Fluent;
using QuestPDF.Helpers;
using QuestPDF.Infrastructure;
Document.Create(container =>
{
container.Page(page =>
{
page.Size(PageSizes.A4);
page.Margin(2, Unit.Centimetre);
page.PageColor(Colors.White);
page.DefaultTextStyle(x => x.FontSize(20));
page.DefaultTextStyle(x => x.FontFamily("Vijaya"));
page.Header()
.Text("தமிழ் PDF!")
.SemiBold().FontSize(36).FontColor(Colors.Blue.Medium);
page.Content()
.PaddingVertical(1, Unit.Centimetre)
.Column(x =>
{
x.Spacing(20);
x.Item().Text("தமிழ் (Tamil language) தமிழர்களினதும் தமிழ் பேசும் பலரின் தாய்மொழி ஆகும். தமிழ், உலகின் உள்ள முதன்மையான மொழிகளில் ஒன்றும் செம்மொழியும் ஆகும்.");
});
page.Footer()
.AlignCenter()
.Text(x =>
{
x.Span("பக்கம் ");
x.CurrentPageNumber();
});
});
})
.GeneratePdf("தமிழ்.pdf");