Edit PDF page so that text is using a different font

Q:

I would like to use PDFNet SDK to edit PDFs by replacing fonts with another version.

I found ContentReplacer sample, but it shows hot to replace text strings with another string … while keeping the existing font.

My problem is different. I want to keep the content as if … except updating fonts.

A:

In general, in case PDF text does not have a valid Unicode encoding (i.e. when you copy text from PDF and paste it in a text editor produces garbage) there is no way to automatically update fonts because the semantic information is missing. In this case the only route that resembles automated processing would be using OCR to reconstruct Unicode mapping (and the below technique to replace the font).

Having said this, :slight_smile: most files these days have searchable text and contain proper Unicode mappings (i.e. you can extract meaningful text).

In this case updating text to use a different font with help of PDFNet is fairly simple.

The following sample code is modeled after ElementEdit sample (you can use it as a drop-in replacement):

//////////////////////
// The sample is in Java (but the same applies to all other supported languages C#, VB, Python, Objective-C, PHP, C++, etc).
import pdftron.Common.PDFNetException;

import pdftron.SDF.SDFDoc;
import pdftron.PDF.*;

public class ElementEditTest {

public static void main(String[] args)
{
PDFNet.initialize();

try
{
PDFDoc doc=new PDFDoc("…/…/TestFiles/numbered.pdf");
doc.initSecurityHandler();
Font new_font = Font.createCIDTrueTypeFont(doc, “C:/Windows/Fonts/comic.ttf”, true, true);

ElementReader reader = new ElementReader();
ElementWriter writer = new ElementWriter();
ElementBuilder builder = new ElementBuilder();

PageIterator itr = doc.getPageIterator();
while (itr.hasNext())
{
Page pg = (Page) (itr.next());
reader.begin(pg);
writer.begin(pg, ElementWriter.e_replacement, false);
Element element = null;
while ((element = reader.next()) != null)
{
if (element.getType() == Element.e_text)
{
String unistr = element.getTextString();
element.getGState().setFont(new_font, element.getGState().getFontSize());
element.setTextData(unistr.getBytes(“UTF-16BE”));
element.updateTextMetrics();
writer.writeElement(element);
}
else
{
writer.writeElement(element);
}
}
reader.end();
writer.end();
}

reader.destroy();
writer.destroy();
builder.destroy();

doc.save("…/…/TestFiles/Output/edited.pdf", SDFDoc.e_remove_unused, null);
doc.close();

}
catch(Exception e)
{
System.out.println(e);
}
}
}