If you use a custom font (anything other than Word’s built-in fonts) in your document, embedding those fonts ensures that whoever views the document sees it the way you intended. In this artilce, we will show you how to embed true type fonts when creating a Word document or saving a Word document to a PDF file, by using Free Spire.Doc for Java.
Embed Fonts in a Word Document
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.PrivateFontPath;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.fields.TextRange;
public class EmbedPrivateFont {
public static void main(String[] args) {
//create a Word document
Document document = new Document();
//add a paragraph
Paragraph paragraph = document.addSection().addParagraph();
//load the private font
PrivateFontPath fontPath = new PrivateFontPath();
fontPath.setFontName("Otto");
fontPath.setFontPath("C:\\Users\\Administrator\\Desktop\\Otto.TTF");
//embed a private font in Word document
document.setEmbedFontsInFile(true);
document.getPrivateFontList().add(fontPath);
//add text to the paragraph and apply the embedded font
TextRange tr = paragraph.appendText("Dev.to \nA publishing platform for developers to share ideas.");
//apply font to text range
tr.getCharacterFormat().setFontName("Otto");
tr.getCharacterFormat().setFontSize(34f);
//save to file
document.saveToFile("EmbedFonts.docx", FileFormat.Docx_2013);
}
}
Embed Fonts in a Converted PDF Document
import com.spire.doc.Document;
import com.spire.doc.PrivateFontPath;
import com.spire.doc.ToPdfParameterList;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.fields.TextRange;
import java.util.*;
public class EmbedPrivateFontInConvertedPDF {
public static void main(String[] args) {
//create a Word document
Document document = new Document();
//add a paragraph
Paragraph paragraph = document.addSection().addParagraph();
//load the private font
PrivateFontPath fontPath = new PrivateFontPath();
fontPath.setFontName("Otto");
fontPath.setFontPath("C:\\Users\\Administrator\\Desktop\\Otto.TTF");
//add text to the paragraph
TextRange tr = paragraph.appendText("Dev.to \nA publishing platform for developers to share ideas.");
//apply font to text range
tr.getCharacterFormat().setFontName("Otto");
tr.getCharacterFormat().setFontSize(34f);
//create a list and add the font path as an element
List<PrivateFontPath> pathList = new LinkedList<>();
pathList.add(fontPath);
//create a ToPdfParameterList object and set the private font paths
ToPdfParameterList toPdfParameterList = new ToPdfParameterList();
toPdfParameterList.setPrivateFontPaths(pathList);
//save the document to PDF
document.saveToFile("EmbedFonts.pdf",toPdfParameterList);
}
}
Top comments (0)