hbrls
hbrls

Reputation: 2150

How to subset the fonts used in a pdf? (with iTextSharp)

I generated a pdf report with ASP.NET + iTextSharp.
I used several types of fonts in it, each font applied to a word or 2 for art reasons.
So the file is large.

How can I only embed the fonts I actually used? Just like what we do with MS Office Options.

MS Office Word 2007 is like this:
"Embed fonts in the file:
Embed only the characters used in the document(best for reducing file size)
Do not embed common system fonts"

OR I can also accept another kind of solution.
Flatten the whole page to a high-resolution picture.
If the programming is convenient, I actually prefer this solution.

Thanks.

Upvotes: 2

Views: 4464

Answers (1)

Mark Storer
Mark Storer

Reputation: 15868

When creating your BaseFont instance with embedding enabled, you need to call myBaseFont.setSubset(true). Note that with the encoding "Identity-H" (AKA BaseFont.IDENTITY_H), this happens automatically:

// find all fonts in the usual places across multiple OSs.
// This can be pretty slow if you have a large number fonts, or the fonts
// themselves are Really Big (ArialUnicodeMS: 23mb).
FontFactory.registerDirectories();

// here's one way to do it, using identity-h forces subsetting
Font myFontSubset1 = FontFactory.getFont(fontName1, BaseFont.IDENTITY_H);

// here's another, explicitly enable subsetting for the underlying BaseFont.
Font myFontSubset2 = FontFactory.getFont(fontName2, FontFactory.defaultEncoding, true);
myFontSubset2.getBaseFont().setSubset(true);

//or you can create the BaseFont yourself, with automagic subsetting
BaseFont myFontSubset3 = BaseFont.createFont(fontPath, BaseFont.IDENTITY_H);

// or create it with some other encoding, and enable subsetting.
BaseFont myFontSubset4 = BaseFont.createFont(fontPath, BaseFont.WINANSI, true);
myFontSubset4.setSubset(true);

Note that this is all Java. In C# the first letter of function names are capitalized and setX(newX) and getX() become properties.

Upvotes: 2

Related Questions