问题
I am using iTextSharp to generate a table and print it on in a pdf. I am trying to change the font but it has zero effect what so ever.
Font tablefont = new Font();
tablefont=FontFactory.GetFont(FontFactory.HELVETICA, 8,BaseColor.RED) ;
table.AddCell("Name :");
PdfPCell cell = new PdfPCell(new Phrase("Star Diamonds") {Font=tablefont});
回答1:
If you are starting a new project, I'd suggest using iText 7 for iTextSharp because we've introduced font inheritance in that version; see Chapter 1: Introducing the PdfFont class
If you insist on using iTextSharp 5.5.9, you should read the old tutorials, and create your Phrase like this:
BaseFont bfTimes = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false);
Font tablefont = new Font(bfTimes, 8);
PdfPCell cell = new PdfPCell(new Phrase("Star Diamonds", tablefont));
Or like this:
Font tablefont = new Font(FontFamily.TIMES_ROMAN, 8);
PdfPCell cell = new PdfPCell(new Phrase("Star Diamonds", tablefont));
Or like this:
Font tablefont = FontFactory.GetFont("Times-Roman", 8);
PdfPCell cell = new PdfPCell(new Phrase("Star Diamonds", tablefont));
You will find plenty of old font examples in chapter 11: Choosing the right font of the iText in Action book. The examples presented on that page are in Java, but if you scroll down, you'll find links to all the corresponding .cs files.
There's also an extensive FAQ section about fonts, consisting of answers to questions that have been posted on StackOverflow in the past.
Although not an exact duplicate, I closed the question by referring to How to use System Font in iTextSharp with VB.net
You are using C#, but the following line is very similar to what you need:
document.Add(New Paragraph("Hello World, Arial.", font))
The Paragraph class is a subclass of the Phrase class that you are using. Just like with Paragraph, you need to pass the font (in your case tablefont) as the second parameter of the constructor.
There's a second reason why I refer to How to use System Font in iTextSharp with VB.net : in the answer to that question, you get very detailed information on how to use any font that is available on your machine.
来源:https://stackoverflow.com/questions/38158112/unable-to-change-font-in-itextsharp