TrueTypeFontSubSet.java
上传用户:jc6688
上传日期:2019-01-12
资源大小:4793k
文件大小:16k
源码类别:

Java编程

开发平台:

Java

  1. /*
  2.  * $Id: TrueTypeFontSubSet.java,v 1.15 2002/07/09 11:28:24 blowagie Exp $
  3.  * $Name:  $
  4.  *
  5.  * Copyright 2001, 2002 Paulo Soares
  6.  *
  7.  * The contents of this file are subject to the Mozilla Public License Version 1.1
  8.  * (the "License"); you may not use this file except in compliance with the License.
  9.  * You may obtain a copy of the License at http://www.mozilla.org/MPL/
  10.  *
  11.  * Software distributed under the License is distributed on an "AS IS" basis,
  12.  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  13.  * for the specific language governing rights and limitations under the License.
  14.  *
  15.  * The Original Code is 'iText, a free JAVA-PDF library'.
  16.  *
  17.  * The Initial Developer of the Original Code is Bruno Lowagie. Portions created by
  18.  * the Initial Developer are Copyright (C) 1999, 2000, 2001, 2002 by Bruno Lowagie.
  19.  * All Rights Reserved.
  20.  * Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
  21.  * are Copyright (C) 2000, 2001, 2002 by Paulo Soares. All Rights Reserved.
  22.  *
  23.  * Contributor(s): all the names of the contributors are added in the source code
  24.  * where applicable.
  25.  *
  26.  * Alternatively, the contents of this file may be used under the terms of the
  27.  * LGPL license (the "GNU LIBRARY GENERAL PUBLIC LICENSE"), in which case the
  28.  * provisions of LGPL are applicable instead of those above.  If you wish to
  29.  * allow use of your version of this file only under the terms of the LGPL
  30.  * License and not to allow others to use your version of this file under
  31.  * the MPL, indicate your decision by deleting the provisions above and
  32.  * replace them with the notice and other provisions required by the LGPL.
  33.  * If you do not delete the provisions above, a recipient may use your version
  34.  * of this file under either the MPL or the GNU LIBRARY GENERAL PUBLIC LICENSE.
  35.  *
  36.  * This library is free software; you can redistribute it and/or modify it
  37.  * under the terms of the MPL as stated above or under the terms of the GNU
  38.  * Library General Public License as published by the Free Software Foundation;
  39.  * either version 2 of the License, or any later version.
  40.  *
  41.  * This library is distributed in the hope that it will be useful, but WITHOUT
  42.  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  43.  * FOR A PARTICULAR PURPOSE. See the GNU Library general Public License for more
  44.  * details.
  45.  *
  46.  * If you didn't download this code from the following link, you should check if
  47.  * you aren't using an obsolete version:
  48.  * http://www.lowagie.com/iText/
  49.  */
  50. package com.lowagie.text.pdf;
  51. import java.io.*;
  52. import java.util.HashMap;
  53. import java.util.ArrayList;
  54. import java.util.Arrays;
  55. import com.lowagie.text.DocumentException;
  56. import com.lowagie.text.ExceptionConverter;
  57. /** Subsets a True Type font by removing the unneeded glyphs from
  58.  * the font.
  59.  *
  60.  * @author  Paulo Soares (psoares@consiste.pt)
  61.  */
  62. class TrueTypeFontSubSet {
  63.     static final String tableNamesSimple[] = {"cvt ", "fpgm", "glyf", "head",
  64.         "hhea", "hmtx", "loca", "maxp", "prep"};
  65.     static final String tableNamesCmap[] = {"cmap", "cvt ", "fpgm", "glyf", "head",
  66.         "hhea", "hmtx", "loca", "maxp", "prep"};
  67.     static final int entrySelectors[] = {0,0,1,1,2,2,2,2,3,3,3,3,3,3,3,3,4,4,4,4,4};
  68.     static final int TABLE_CHECKSUM = 0;
  69.     static final int TABLE_OFFSET = 1;
  70.     static final int TABLE_LENGTH = 2;
  71.     static final int HEAD_LOCA_FORMAT_OFFSET = 51;
  72.     static final int ARG_1_AND_2_ARE_WORDS = 1;
  73.     static final int WE_HAVE_A_SCALE = 8;
  74.     static final int MORE_COMPONENTS = 32;
  75.     static final int WE_HAVE_AN_X_AND_Y_SCALE = 64;
  76.     static final int WE_HAVE_A_TWO_BY_TWO = 128;
  77.     
  78.     
  79.     /** Contains the location of the several tables. The key is the name of
  80.      * the table and the value is an <CODE>int[3]</CODE> where position 0
  81.      * is the checksum, position 1 is the offset from the start of the file
  82.      * and position 2 is the length of the table.
  83.      */
  84.     protected HashMap tableDirectory;
  85.     /** The file in use.
  86.      */
  87.     protected RandomAccessFileOrArray rf;
  88.     /** The file name.
  89.      */
  90.     protected String fileName;
  91.     protected boolean includeCmap;
  92.     protected boolean locaShortTable;
  93.     protected int locaTable[];
  94.     protected HashMap glyphsUsed;
  95.     protected ArrayList glyphsInList;
  96.     protected int tableGlyphOffset;
  97.     protected int newLocaTable[];
  98.     protected byte newLocaTableOut[];
  99.     protected byte newGlyfTable[];
  100.     protected int glyfTableRealSize;
  101.     protected int locaTableRealSize;
  102.     protected byte outFont[];
  103.     protected int fontPtr;
  104.     protected int directoryOffset;
  105.     /** Creates a new TrueTypeFontSubSet
  106.      * @param directoryOffset The offset from the start of the file to the table directory
  107.      * @param fileName the file name of the font
  108.      * @param glyphsUsed the glyphs used
  109.      * @param includeCmap <CODE>true</CODE> if the table cmap is to be included in the generated font
  110.      */
  111.     TrueTypeFontSubSet(String fileName, RandomAccessFileOrArray rf, HashMap glyphsUsed, int directoryOffset, boolean includeCmap) {
  112.         this.fileName = fileName;
  113.         this.rf = rf;
  114.         this.glyphsUsed = glyphsUsed;
  115.         this.includeCmap = includeCmap;
  116.         this.directoryOffset = directoryOffset;
  117.         glyphsInList = new ArrayList(glyphsUsed.keySet());
  118.     }
  119.     
  120.     /** Does the actual work of subsetting the font.
  121.      * @throws IOException on error
  122.      * @throws DocumentException on error
  123.      * @return the subset font
  124.      */    
  125.     byte[] process() throws IOException, DocumentException {
  126.         try {
  127.             rf.reOpen();
  128.             createTableDirectory();
  129.             readLoca();
  130.             flatGlyphs();
  131.             createNewGlyphTables();
  132.             locaTobytes();
  133.             assembleFont();
  134.             return outFont;
  135.         }
  136.         finally {
  137.             try {
  138.                 rf.close();
  139.             }
  140.             catch (Exception e) {
  141.                 // empty on purpose
  142.             }
  143.         }
  144.     }
  145.     
  146.     protected void assembleFont() throws IOException, DocumentException {
  147.         int tableLocation[];
  148.         int fullFontSize = 0;
  149.         String tableNames[];
  150.         if (includeCmap)
  151.             tableNames = tableNamesCmap;
  152.         else
  153.             tableNames = tableNamesSimple;
  154.         int tablesUsed = 2;
  155.         int len = 0;
  156.         for (int k = 0; k < tableNames.length; ++k) {
  157.             String name = tableNames[k];
  158.             if (name.equals("glyf") || name.equals("loca"))
  159.                 continue;
  160.             tableLocation = (int[])tableDirectory.get(name);
  161.             if (tableLocation == null)
  162.                 continue;
  163.             ++tablesUsed;
  164.             fullFontSize += (tableLocation[TABLE_LENGTH] + 3) & (~3);
  165.         }
  166.         fullFontSize += newLocaTableOut.length;
  167.         fullFontSize += newGlyfTable.length;
  168.         int ref = 16 * tablesUsed + 12;
  169.         fullFontSize += ref;
  170.         outFont = new byte[fullFontSize];
  171.         fontPtr = 0;
  172.         writeFontInt(0x00010000);
  173.         writeFontShort(tablesUsed);
  174.         int selector = entrySelectors[tablesUsed];
  175.         writeFontShort((1 << selector) * 16);
  176.         writeFontShort(selector);
  177.         writeFontShort((tablesUsed - (1 << selector)) * 16);
  178.         for (int k = 0; k < tableNames.length; ++k) {
  179.             String name = tableNames[k];
  180.             tableLocation = (int[])tableDirectory.get(name);
  181.             if (tableLocation == null)
  182.                 continue;
  183.             writeFontString(name);
  184.             if (name.equals("glyf")) {
  185.                 writeFontInt(calculateChecksum(newGlyfTable));
  186.                 len = glyfTableRealSize;
  187.             }
  188.             else if (name.equals("loca")) {
  189.                 writeFontInt(calculateChecksum(newLocaTableOut));
  190.                 len = locaTableRealSize;
  191.             }
  192.             else {
  193.                 writeFontInt(tableLocation[TABLE_CHECKSUM]);
  194.                 len = tableLocation[TABLE_LENGTH];
  195.             }
  196.             writeFontInt(ref);
  197.             writeFontInt(len);
  198.             ref += (len + 3) & (~3);
  199.         }
  200.         for (int k = 0; k < tableNames.length; ++k) {
  201.             String name = tableNames[k];
  202.             tableLocation = (int[])tableDirectory.get(name);
  203.             if (tableLocation == null)
  204.                 continue;
  205.             if (name.equals("glyf")) {
  206.                 System.arraycopy(newGlyfTable, 0, outFont, fontPtr, newGlyfTable.length);
  207.                 fontPtr += newGlyfTable.length;
  208.                 newGlyfTable = null;
  209.             }
  210.             else if (name.equals("loca")) {
  211.                 System.arraycopy(newLocaTableOut, 0, outFont, fontPtr, newLocaTableOut.length);
  212.                 fontPtr += newLocaTableOut.length;
  213.                 newLocaTableOut = null;
  214.             }
  215.             else {
  216.                 rf.seek(tableLocation[TABLE_OFFSET]);
  217.                 rf.readFully(outFont, fontPtr, tableLocation[TABLE_LENGTH]);
  218.                 fontPtr += (tableLocation[TABLE_LENGTH] + 3) & (~3);
  219.             }
  220.         }
  221.     }
  222.     
  223.     protected void createTableDirectory() throws IOException, DocumentException {
  224.         tableDirectory = new HashMap();
  225.         rf.seek(directoryOffset);
  226.         int id = rf.readInt();
  227.         if (id != 0x00010000)
  228.             throw new DocumentException(fileName + " is not a true type file.");
  229.         int num_tables = rf.readUnsignedShort();
  230.         rf.skipBytes(6);
  231.         for (int k = 0; k < num_tables; ++k) {
  232.             String tag = readStandardString(4);
  233.             int tableLocation[] = new int[3];
  234.             tableLocation[TABLE_CHECKSUM] = rf.readInt();
  235.             tableLocation[TABLE_OFFSET] = rf.readInt();
  236.             tableLocation[TABLE_LENGTH] = rf.readInt();
  237.             tableDirectory.put(tag, tableLocation);
  238.         }
  239.     }
  240.     
  241.     protected void readLoca() throws IOException, DocumentException {
  242.         int tableLocation[];
  243.         tableLocation = (int[])tableDirectory.get("head");
  244.         if (tableLocation == null)
  245.             throw new DocumentException("Table 'head' does not exist in " + fileName);
  246.         rf.seek(tableLocation[TABLE_OFFSET] + HEAD_LOCA_FORMAT_OFFSET);
  247.         locaShortTable = (rf.readUnsignedShort() == 0);
  248.         tableLocation = (int[])tableDirectory.get("loca");
  249.         if (tableLocation == null)
  250.             throw new DocumentException("Table 'loca' does not exist in " + fileName);
  251.         rf.seek(tableLocation[TABLE_OFFSET]);
  252.         if (locaShortTable) {
  253.             int entries = tableLocation[TABLE_LENGTH] / 2;
  254.             locaTable = new int[entries];
  255.             for (int k = 0; k < entries; ++k)
  256.                 locaTable[k] = rf.readUnsignedShort() * 2;
  257.         }
  258.         else {
  259.             int entries = tableLocation[TABLE_LENGTH] / 4;
  260.             locaTable = new int[entries];
  261.             for (int k = 0; k < entries; ++k)
  262.                 locaTable[k] = rf.readInt();
  263.         }
  264.     }
  265.     
  266.     protected void createNewGlyphTables() throws IOException {
  267.         newLocaTable = new int[locaTable.length];
  268.         int activeGlyphs[] = new int[glyphsInList.size()];
  269.         for (int k = 0; k < activeGlyphs.length; ++k)
  270.             activeGlyphs[k] = ((Integer)glyphsInList.get(k)).intValue();
  271.         Arrays.sort(activeGlyphs);
  272.         int glyfSize = 0;
  273.         for (int k = 0; k < activeGlyphs.length; ++k) {
  274.             int glyph = activeGlyphs[k];
  275.             glyfSize += locaTable[glyph + 1] - locaTable[glyph];
  276.         }
  277.         glyfTableRealSize = glyfSize;
  278.         glyfSize = (glyfSize + 3) & (~3);
  279.         newGlyfTable = new byte[glyfSize];
  280.         int glyfPtr = 0;
  281.         int listGlyf = 0;
  282.         for (int k = 0; k < newLocaTable.length; ++k) {
  283.             newLocaTable[k] = glyfPtr;
  284.             if (listGlyf < activeGlyphs.length && activeGlyphs[listGlyf] == k) {
  285.                 ++listGlyf;
  286.                 newLocaTable[k] = glyfPtr;
  287.                 int start = locaTable[k];
  288.                 int len = locaTable[k + 1] - start;
  289.                 if (len > 0) {
  290.                     rf.seek(tableGlyphOffset + start);
  291.                     rf.readFully(newGlyfTable, glyfPtr, len);
  292.                     glyfPtr += len;
  293.                 }
  294.             }
  295.         }
  296.     }
  297.     
  298.     protected void locaTobytes() {
  299.         if (locaShortTable)
  300.             locaTableRealSize = newLocaTable.length * 2;
  301.         else
  302.             locaTableRealSize = newLocaTable.length * 4;
  303.         newLocaTableOut = new byte[(locaTableRealSize + 3) & (~3)];
  304.         outFont = newLocaTableOut;
  305.         fontPtr = 0;
  306.         for (int k = 0; k < newLocaTable.length; ++k) {
  307.             if (locaShortTable)
  308.                 writeFontShort(newLocaTable[k] / 2);
  309.             else
  310.                 writeFontInt(newLocaTable[k]);
  311.         }
  312.         
  313.     }
  314.     
  315.     protected void flatGlyphs() throws IOException, DocumentException {
  316.         int tableLocation[];
  317.         tableLocation = (int[])tableDirectory.get("glyf");
  318.         if (tableLocation == null)
  319.             throw new DocumentException("Table 'glyf' does not exist in " + fileName);
  320.         Integer glyph0 = new Integer(0);
  321.         if (!glyphsUsed.containsKey(glyph0)) {
  322.             glyphsUsed.put(glyph0, null);
  323.             glyphsInList.add(glyph0);
  324.         }
  325.         tableGlyphOffset = tableLocation[TABLE_OFFSET];
  326.         for (int k = 0; k < glyphsInList.size(); ++k) {
  327.             int glyph = ((Integer)glyphsInList.get(k)).intValue();
  328.             checkGlyphComposite(glyph);
  329.         }
  330.     }
  331.     protected void checkGlyphComposite(int glyph) throws IOException {
  332.         int start = locaTable[glyph];
  333.         if (start == locaTable[glyph + 1]) // no contour
  334.             return;
  335.         rf.seek(tableGlyphOffset + start);
  336.         int numContours = rf.readShort();
  337.         if (numContours >= 0)
  338.             return;
  339.         rf.skipBytes(8);
  340.         for(;;) {
  341.             int flags = rf.readUnsignedShort();
  342.             Integer cGlyph = new Integer(rf.readUnsignedShort());
  343.             if (!glyphsUsed.containsKey(cGlyph)) {
  344.                 glyphsUsed.put(cGlyph, null);
  345.                 glyphsInList.add(cGlyph);
  346.             }
  347.             if ((flags & MORE_COMPONENTS) == 0)
  348.                 return;
  349.             int skip;
  350.             if ((flags & ARG_1_AND_2_ARE_WORDS) != 0)
  351.                 skip = 4;
  352.             else
  353.                 skip = 2;
  354.             if ((flags & WE_HAVE_A_SCALE) != 0)
  355.                 skip += 2;
  356.             else if ((flags & WE_HAVE_AN_X_AND_Y_SCALE) != 0)
  357.                 skip += 4;
  358.             if ((flags & WE_HAVE_A_TWO_BY_TWO) != 0)
  359.                 skip += 8;
  360.             rf.skipBytes(skip);
  361.         }
  362.     }
  363.     
  364.     /** Reads a <CODE>String</CODE> from the font file as bytes using the Cp1252
  365.      *  encoding.
  366.      * @param length the length of bytes to read
  367.      * @return the <CODE>String</CODE> read
  368.      * @throws IOException the font file could not be read
  369.      */
  370.     protected String readStandardString(int length) throws IOException {
  371.         byte buf[] = new byte[length];
  372.         rf.readFully(buf);
  373.         try {
  374.             return new String(buf, BaseFont.WINANSI);
  375.         }
  376.         catch (Exception e) {
  377.             throw new ExceptionConverter(e);
  378.         }
  379.     }
  380.     
  381.     protected void writeFontShort(int n) {
  382.         outFont[fontPtr++] = (byte)(n >> 8);
  383.         outFont[fontPtr++] = (byte)(n);
  384.     }
  385.     protected void writeFontInt(int n) {
  386.         outFont[fontPtr++] = (byte)(n >> 24);
  387.         outFont[fontPtr++] = (byte)(n >> 16);
  388.         outFont[fontPtr++] = (byte)(n >> 8);
  389.         outFont[fontPtr++] = (byte)(n);
  390.     }
  391.     protected void writeFontString(String s) {
  392.         byte b[] = PdfEncodings.convertToBytes(s, BaseFont.WINANSI);
  393.         System.arraycopy(b, 0, outFont, fontPtr, b.length);
  394.         fontPtr += b.length;
  395.     }
  396.     
  397.     protected int calculateChecksum(byte b[]) {
  398.         int len = b.length / 4;
  399.         int v0 = 0;
  400.         int v1 = 0;
  401.         int v2 = 0;
  402.         int v3 = 0;
  403.         int ptr = 0;
  404.         for (int k = 0; k < len; ++k) {
  405.             v3 += (int)b[ptr++] & 0xff;
  406.             v2 += (int)b[ptr++] & 0xff;
  407.             v1 += (int)b[ptr++] & 0xff;
  408.             v0 += (int)b[ptr++] & 0xff;
  409.         }
  410.         return v0 + (v1 << 8) + (v2 << 16) + (v3 << 24);
  411.     }
  412. }