Fonts and merging documents

31st May 2016
admin-marketing
MergeAndAddFont.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
/*
    This file is part of the iText (R) project.
    Copyright (c) 1998-2019 iText Group NV
    Authors: iText Software.
 
    For more information, please contact iText Software at this address:
    sales@itextpdf.com
 */
package com.itextpdf.samples.sandbox.fonts;
 
import com.itextpdf.io.font.PdfEncodings;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.pdf.*;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Paragraph;
 
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
 
public class MergeAndAddFont {
    public static final String FONT =
            "./src/test/resources/font/GravitasOne.ttf";
 
    public static final String[] FILE_A = {
            "./target/sandbox/fonts/testA1.pdf", "./target/sandbox/fonts/testA2.pdf",
            "./target/sandbox/fonts/testA3.pdf"
    };
    public static final String[] FILE_B = {
            "./target/sandbox/fonts/testB1.pdf", "./target/sandbox/fonts/testB2.pdf",
            "./target/sandbox/fonts/testB3.pdf"
    };
    public static final String[] FILE_C = {
            "./target/sandbox/fonts/testC1.pdf", "./target/sandbox/fonts/testC2.pdf",
            "./target/sandbox/fonts/testC3.pdf"
    };
    public static final String[] CONTENT = {
            "abcdefgh", "ijklmnopq", "rstuvwxyz"
    };
    public static final String MERGED_A1 =
            "./target/sandbox/fonts/testA_merged1.pdf";
    public static final String MERGED_A2 =
            "./target/sandbox/fonts/testA_merged2.pdf";
    public static final String MERGED_B1 =
            "./target/sandbox/fonts/testB_merged1.pdf";
    public static final String MERGED_B2 =
            "./target/sandbox/fonts/testB_merged2.pdf";
    public static final String MERGED_C1 =
            "./target/sandbox/fonts/testC_merged1.pdf";
    public static final String MERGED_C2 =
            "./target/sandbox/fonts/testC_merged2.pdf";
 
    // we will check via CompareTool only one result file.
    public static final String DEST =
            MERGED_C1;
 
    public static void main(String[] args) throws Exception {
        File file = new File(DEST);
        file.getParentFile().mkdirs();
        new MergeAndAddFont().manipulatePdf(DEST);
    }
 
    public void createPdf(String filename, String text, boolean embedded, boolean subset) throws IOException {
        PdfDocument pdfDoc = new PdfDocument(new PdfWriter(filename));
        Document doc = new Document(pdfDoc);
        PdfFont font = PdfFontFactory.createFont(FONT, PdfEncodings.WINANSI, embedded);
        font.setSubset(subset);
        doc.add(new Paragraph(text).setFont(font));
        doc.close();
    }
 
    public void mergeFiles(String[] files, String result, boolean isSmartModeOn) throws IOException {
        PdfWriter writer = new PdfWriter(result);
        writer.setSmartMode(isSmartModeOn);
        PdfDocument pdfDoc = new PdfDocument(writer);
        pdfDoc.initializeOutlines();
        for (int i = 0; i < files.length; i++) {
            PdfDocument addedDoc = new PdfDocument(new PdfReader(files[i]));
            addedDoc.copyPagesTo(1, addedDoc.getNumberOfPages(), pdfDoc);
            addedDoc.close();
        }
        pdfDoc.close();
    }
 
    protected void manipulatePdf(String dest) throws Exception {
        MergeAndAddFont app = new MergeAndAddFont();
 
        for (int i = 0; i < FILE_A.length; i++) {
            app.createPdf(FILE_A[i], CONTENT[i], true, true);
        }
        app.mergeFiles(FILE_A, MERGED_A1, false);
        app.mergeFiles(FILE_A, MERGED_A2, true);
 
        for (int i = 0; i < FILE_B.length; i++) {
            app.createPdf(FILE_B[i], CONTENT[i], true, false);
        }
        app.mergeFiles(FILE_B, MERGED_B1, false);
        app.mergeFiles(FILE_B, MERGED_B2, true);
 
        for (int i = 0; i < FILE_C.length; i++) {
            app.createPdf(FILE_C[i], CONTENT[i], false, false);
        }
        app.mergeFiles(FILE_C, MERGED_C1, true);
        app.embedFont(MERGED_C1, FONT, MERGED_C2);
    }
 
    protected void embedFont(String merged, String fontfile, String result) throws IOException {
        // the font file
        RandomAccessFile raf = new RandomAccessFile(fontfile, "r");
        byte fontbytes[] = new byte[(int) raf.length()];
        raf.readFully(fontbytes);
        raf.close();
        // create a new stream for the font file
        PdfStream stream = new PdfStream(fontbytes);
        stream.setCompressionLevel(CompressionConstants.DEFAULT_COMPRESSION);
        stream.put(PdfName.Length1, new PdfNumber(fontbytes.length));
        // create a reader object
        PdfObject object;
        PdfDictionary font;
        PdfDocument pdfDoc = new PdfDocument(new PdfReader(merged), new PdfWriter(result));
        PdfName fontname = new PdfName(PdfFontFactory.createFont(fontfile, PdfEncodings.WINANSI)
                .getFontProgram().getFontNames().getFontName());
        int n = pdfDoc.getNumberOfPdfObjects();
        for (int i = 0; i < n; i++) {
            object = pdfDoc.getPdfObject(i);
            if (object == null || !object.isDictionary()) {
                continue;
            }
            font = (PdfDictionary) object;
            if (PdfName.FontDescriptor.equals(font.get(PdfName.Type))
                    && fontname.equals(font.get(PdfName.FontName))) {
                font.put(PdfName.FontFile2, stream.makeIndirect(pdfDoc).getIndirectReference());
            }
        }
        pdfDoc.close();
    }
}
MergeAndAddFont.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
/*
    This file is part of the iText (R) project.
    Copyright (c) 1998-2019 iText Group NV
    Authors: iText Software.
 
    For more information, please contact iText Software at this address:
    sales@itextpdf.com
 */
 
using System;
using System.Collections.Generic;
using System.IO;
using iText.IO.Font;
using iText.Kernel.Font;
using iText.Kernel.Pdf;
using iText.Layout;
using iText.Layout.Element;
 
namespace iText.Samples.Sandbox.Fonts
{
    public class MergeAndAddFont
    {
        public static readonly String FONT = "../../resources/font/GravitasOne.ttf";
 
        public static readonly String[] FILE_A =
        {
            "../../results/sandbox/fonts/testA1.pdf",
            "../../results/sandbox/fonts/testA2.pdf",
            "../../results/sandbox/fonts/testA3.pdf"
        };
 
        public static readonly String[] FILE_B =
        {
            "../../results/sandbox/fonts/testB1.pdf",
            "../../results/sandbox/fonts/testB2.pdf",
            "../../results/sandbox/fonts/testB3.pdf"
        };
 
        public static readonly String[] FILE_C =
        {
            "../../results/sandbox/fonts/testC1.pdf",
            "../../results/sandbox/fonts/testC2.pdf",
            "../../results/sandbox/fonts/testC3.pdf"
        };
 
        public static readonly String[] CONTENT =
        {
            "abcdefgh", "ijklmnopq", "rstuvwxyz"
        };
 
        public static readonly Dictionary<String, String> DEST_NAMES = new Dictionary<string, string>();
 
        static MergeAndAddFont()
        {
            DEST_NAMES.Add("A1", "testA_merged1.pdf");
            DEST_NAMES.Add("A2", "testA_merged2.pdf");
            DEST_NAMES.Add("B1", "testB_merged1.pdf");
            DEST_NAMES.Add("B2", "testB_merged2.pdf");
            DEST_NAMES.Add("C1", "testC_merged1.pdf");
            DEST_NAMES.Add("C2", "testC_merged2.pdf");
        }
 
        public static readonly String DEST = "../../results/sandbox/fonts/";
 
        public static void Main(String[] args)
        {
            FileInfo file = new FileInfo(DEST);
            file.Directory.Create();
 
            new MergeAndAddFont().ManipulatePdf(DEST);
        }
 
        public void CreatePdf(String filename, String text, bool embedded, bool subset)
        {
            PdfDocument pdfDoc = new PdfDocument(new PdfWriter(filename));
            Document doc = new Document(pdfDoc);
 
            // The 3rd parameter indicates whether the font is to be embedded into the target document.
            PdfFont font = PdfFontFactory.CreateFont(FONT, PdfEncodings.WINANSI, embedded);
 
            // When set to true, only the used glyphs will be included in the font.
            // When set to false, the full font will be included and all subset ranges will be removed.
            font.SetSubset(subset);
            doc.Add(new Paragraph(text).SetFont(font));
 
            doc.Close();
        }
 
        public void MergeFiles(String[] files, String result, bool isSmartModeOn)
        {
            PdfWriter writer = new PdfWriter(result);
 
            // In smart mode when resources (such as fonts, images,...) are encountered,
            // a reference to these resources is saved in a cache and can be reused.
            // This mode reduces the file size of the resulting PDF document.
            writer.SetSmartMode(isSmartModeOn);
            PdfDocument pdfDoc = new PdfDocument(writer);
 
            // This method initializes an outline tree of the document and sets outline mode to true.
            pdfDoc.InitializeOutlines();
 
            for (int i = 0; i < files.Length; i++)
            {
                PdfDocument addedDoc = new PdfDocument(new PdfReader(files[i]));
                addedDoc.CopyPagesTo(1, addedDoc.GetNumberOfPages(), pdfDoc);
                addedDoc.Close();
            }
 
            pdfDoc.Close();
        }
 
        protected void ManipulatePdf(String dest)
        {
            for (int i = 0; i < FILE_A.Length; i++)
            {
                
                // Create pdf files with font, which will be embedded into the target document,
                // and only the used glyphs will be included in the font.
                CreatePdf(FILE_A[i], CONTENT[i], true, true);
            }
 
            MergeFiles(FILE_A, dest + DEST_NAMES["A1"], false);
            MergeFiles(FILE_A, dest + DEST_NAMES["A2"], true);
 
            for (int i = 0; i < FILE_B.Length; i++)
            {
                
                // Create pdf files with font, which will embedded into the target document.
                // Full font will be included and all subset ranges will be removed
                CreatePdf(FILE_B[i], CONTENT[i], true, false);
            }
 
            MergeFiles(FILE_B, dest + DEST_NAMES["B1"], false);
            MergeFiles(FILE_B, dest + DEST_NAMES["B2"], true);
 
            for (int i = 0; i < FILE_C.Length; i++)
            {
                
                // Create pdf files with font, which won't be embedded into the target document.
                // Full font will be included and all subset ranges will be removed
                CreatePdf(FILE_C[i], CONTENT[i], false, false);
            }
 
            MergeFiles(FILE_C, dest + DEST_NAMES["C1"], true);
 
            // Embed the font manually
            EmbedFont(dest + DEST_NAMES["C1"], FONT, dest + DEST_NAMES["C2"]);
        }
 
        protected void EmbedFont(String merged, String fontfile, String result)
        {
            
            // The font file
            FileStream raf = new FileStream(fontfile, FileMode.Open, FileAccess.Read);
            byte[] fontbytes = new byte[(int) raf.Length];
            raf.Read(fontbytes, 0, fontbytes.Length);
            raf.Close();
 
            // Create a new stream for the font file
            PdfStream stream = new PdfStream(fontbytes);
            stream.SetCompressionLevel(CompressionConstants.DEFAULT_COMPRESSION);
            stream.Put(PdfName.Length1, new PdfNumber(fontbytes.Length));
 
            PdfDocument pdfDoc = new PdfDocument(new PdfReader(merged), new PdfWriter(result));
            int numberOfPdfObjects = pdfDoc.GetNumberOfPdfObjects();
 
            // Search for the font dictionary
            for (int i = 0; i < numberOfPdfObjects; i++)
            {
                PdfObject pdfObject = pdfDoc.GetPdfObject(i);
                if (pdfObject == null || !pdfObject.IsDictionary())
                {
                    continue;
                }
 
                PdfDictionary fontDictionary = (PdfDictionary) pdfObject;
                PdfFont font = PdfFontFactory.CreateFont(fontfile, PdfEncodings.WINANSI);
                PdfName fontname = new PdfName(font.GetFontProgram().GetFontNames().GetFontName());
                if (PdfName.FontDescriptor.Equals(fontDictionary.Get(PdfName.Type))
                    && fontname.Equals(fontDictionary.Get(PdfName.FontName)))
                {
                    
                    // Embed the passed font to the pdf document
                    fontDictionary.Put(PdfName.FontFile2, stream.MakeIndirect(pdfDoc).GetIndirectReference());
                }
            }
 
            pdfDoc.Close();
        }
    }
}

Click the following link to see the legacy example for iText 5. Except for security fixes, iText 5 is no longer being developed.



Contact

Still have questions? 

We're happy to answer your questions. Reach out to us and we'll get back to you shortly.

Contact us
Stay updated

Join 11,000+ subscribers and become an iText PDF expert by staying up to date with our new products, updates, tips, technical solutions and happenings.

Subscribe Now