Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

HWPFOldDocument.java 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. /* ====================================================================
  2. Licensed to the Apache Software Foundation (ASF) under one or more
  3. contributor license agreements. See the NOTICE file distributed with
  4. this work for additional information regarding copyright ownership.
  5. The ASF licenses this file to You under the Apache License, Version 2.0
  6. (the "License"); you may not use this file except in compliance with
  7. the License. You may obtain a copy of the License at
  8. http://www.apache.org/licenses/LICENSE-2.0
  9. Unless required by applicable law or agreed to in writing, software
  10. distributed under the License is distributed on an "AS IS" BASIS,
  11. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. See the License for the specific language governing permissions and
  13. limitations under the License.
  14. ==================================================================== */
  15. package org.apache.poi.hwpf;
  16. import java.io.File;
  17. import java.io.IOException;
  18. import java.io.OutputStream;
  19. import java.io.UnsupportedEncodingException;
  20. import java.nio.charset.Charset;
  21. import org.apache.poi.hpsf.CustomProperties;
  22. import org.apache.poi.hpsf.DocumentSummaryInformation;
  23. import org.apache.poi.hpsf.Section;
  24. import org.apache.poi.hwmf.record.HwmfFont;
  25. import org.apache.poi.hwpf.model.ComplexFileTable;
  26. import org.apache.poi.hwpf.model.FontTable;
  27. import org.apache.poi.hwpf.model.OldCHPBinTable;
  28. import org.apache.poi.hwpf.model.OldComplexFileTable;
  29. import org.apache.poi.hwpf.model.OldFfn;
  30. import org.apache.poi.hwpf.model.OldFontTable;
  31. import org.apache.poi.hwpf.model.OldPAPBinTable;
  32. import org.apache.poi.hwpf.model.OldSectionTable;
  33. import org.apache.poi.hwpf.model.OldTextPieceTable;
  34. import org.apache.poi.hwpf.model.PieceDescriptor;
  35. import org.apache.poi.hwpf.model.TextPiece;
  36. import org.apache.poi.hwpf.model.TextPieceTable;
  37. import org.apache.poi.hwpf.usermodel.Range;
  38. import org.apache.poi.poifs.filesystem.DirectoryNode;
  39. import org.apache.poi.poifs.filesystem.POIFSFileSystem;
  40. import org.apache.poi.util.CodePageUtil;
  41. import org.apache.poi.util.LittleEndian;
  42. import org.apache.poi.util.NotImplemented;
  43. import org.apache.poi.util.POILogFactory;
  44. import org.apache.poi.util.POILogger;
  45. import org.apache.poi.util.StringUtil;
  46. /**
  47. * Provides very simple support for old (Word 6 / Word 95)
  48. * files.
  49. */
  50. public class HWPFOldDocument extends HWPFDocumentCore {
  51. private static final POILogger logger = POILogFactory
  52. .getLogger( HWPFOldDocument.class );
  53. private final static Charset DEFAULT_CHARSET = StringUtil.WIN_1252;
  54. private OldTextPieceTable tpt;
  55. private StringBuilder _text;
  56. private final OldFontTable fontTable;
  57. private final Charset guessedCharset;
  58. public HWPFOldDocument(POIFSFileSystem fs) throws IOException {
  59. this(fs.getRoot());
  60. }
  61. public HWPFOldDocument(DirectoryNode directory)
  62. throws IOException {
  63. super(directory);
  64. // Where are things?
  65. int sedTableOffset = LittleEndian.getInt(_mainStream, 0x88);
  66. int sedTableSize = LittleEndian.getInt(_mainStream, 0x8c);
  67. int chpTableOffset = LittleEndian.getInt(_mainStream, 0xb8);
  68. int chpTableSize = LittleEndian.getInt(_mainStream, 0xbc);
  69. int papTableOffset = LittleEndian.getInt(_mainStream, 0xc0);
  70. int papTableSize = LittleEndian.getInt(_mainStream, 0xc4);
  71. int fontTableOffset = LittleEndian.getInt(_mainStream, 0xd0);
  72. int fontTableSize = LittleEndian.getInt(_mainStream, 0xd4);
  73. fontTable = new OldFontTable(_mainStream, fontTableOffset, fontTableSize);
  74. //TODO: figure out how to map runs/text pieces to fonts
  75. //for now, if there's a non standard codepage in one of the fonts
  76. //assume that the doc is in that codepage.
  77. guessedCharset = guessCodePage(fontTable);
  78. int complexTableOffset = LittleEndian.getInt(_mainStream, 0x160);
  79. // We need to get hold of the text that makes up the
  80. // document, which might be regular or fast-saved
  81. ComplexFileTable cft = null;
  82. if(_fib.getFibBase().isFComplex()) {
  83. cft = new OldComplexFileTable(
  84. _mainStream, _mainStream,
  85. complexTableOffset, _fib.getFibBase().getFcMin(), guessedCharset
  86. );
  87. tpt = (OldTextPieceTable)cft.getTextPieceTable();
  88. } else {
  89. // TODO Discover if these older documents can ever hold Unicode Strings?
  90. // (We think not, because they seem to lack a Piece table)
  91. //
  92. // What we have here is a wretched hack. We need to figure out
  93. // how to get the correct charset for the doc.
  94. TextPiece tp = null;
  95. try {
  96. tp = buildTextPiece(guessedCharset);
  97. } catch (IllegalStateException e) {
  98. //if there was a problem with the guessed charset and the length of the
  99. //textpiece, back off to win1252. This is effectively what we used to do.
  100. tp = buildTextPiece(StringUtil.WIN_1252);
  101. logger.log(POILogger.WARN, "Error with "+guessedCharset +". Backing off to Windows-1252");
  102. }
  103. tpt.add(tp);
  104. }
  105. _text = tpt.getText();
  106. // Now we can fetch the character and paragraph properties
  107. _cbt = new OldCHPBinTable(
  108. _mainStream, chpTableOffset, chpTableSize,
  109. _fib.getFibBase().getFcMin(), tpt
  110. );
  111. _pbt = new OldPAPBinTable(
  112. _mainStream, papTableOffset, papTableSize,
  113. _fib.getFibBase().getFcMin(), tpt
  114. );
  115. _st = new OldSectionTable(
  116. _mainStream, sedTableOffset, sedTableSize,
  117. _fib.getFibBase().getFcMin(), tpt
  118. );
  119. /*
  120. * in this mode we preserving PAPX/CHPX structure from file, so text may
  121. * miss from output, and text order may be corrupted
  122. */
  123. boolean preserveBinTables = false;
  124. try
  125. {
  126. preserveBinTables = Boolean.parseBoolean( System
  127. .getProperty( HWPFDocument.PROPERTY_PRESERVE_BIN_TABLES ) );
  128. }
  129. catch ( Exception exc )
  130. {
  131. // ignore;
  132. }
  133. if ( !preserveBinTables )
  134. {
  135. _cbt.rebuild( cft );
  136. _pbt.rebuild( _text, cft );
  137. }
  138. }
  139. /**
  140. *
  141. * @param guessedCharset charset that we think this is
  142. * @return a new text piece
  143. * @throws IllegalStateException if the length isn't correct
  144. */
  145. private TextPiece buildTextPiece(Charset guessedCharset) throws IllegalStateException {
  146. PieceDescriptor pd = new PieceDescriptor(new byte[] {0,0, 0,0,0,127, 0,0}, 0, guessedCharset);
  147. pd.setFilePosition(_fib.getFibBase().getFcMin());
  148. // Generate a single Text Piece Table, with a single Text Piece
  149. // which covers all the (8 bit only) text in the file
  150. tpt = new OldTextPieceTable();
  151. byte[] textData = new byte[_fib.getFibBase().getFcMac()-_fib.getFibBase().getFcMin()];
  152. System.arraycopy(_mainStream, _fib.getFibBase().getFcMin(), textData, 0, textData.length);
  153. int numChars = textData.length;
  154. if (CodePageUtil.DOUBLE_BYTE_CHARSETS.contains(guessedCharset)) {
  155. numChars /= 2;
  156. }
  157. return new TextPiece(
  158. 0, numChars, textData, pd
  159. );
  160. }
  161. /**
  162. * Try to get the code page from various areas of the document.
  163. * Start with the DocumentSummaryInformation, back off to the section info,
  164. * finally try the charset information from the font table.
  165. *
  166. * Consider throwing an exception if > 1 unique codepage that is not default, symbol or ansi
  167. * appears here.
  168. *
  169. * @param fontTable
  170. * @return The detected Charset from the old font table
  171. */
  172. private Charset guessCodePage(OldFontTable fontTable) {
  173. // pick the first non-default, non-symbol charset
  174. for (OldFfn oldFfn : fontTable.getFontNames()) {
  175. HwmfFont.WmfCharset wmfCharset = HwmfFont.WmfCharset.valueOf(oldFfn.getChs()& 0xff);
  176. if (wmfCharset != null &&
  177. wmfCharset != HwmfFont.WmfCharset.ANSI_CHARSET &&
  178. wmfCharset != HwmfFont.WmfCharset.DEFAULT_CHARSET &&
  179. wmfCharset != HwmfFont.WmfCharset.SYMBOL_CHARSET ) {
  180. return wmfCharset.getCharset();
  181. }
  182. }
  183. logger.log(POILogger.WARN, "Couldn't find a defined charset; backing off to cp1252");
  184. //if all else fails
  185. return DEFAULT_CHARSET;
  186. }
  187. public Range getOverallRange()
  188. {
  189. // Life is easy when we have no footers, headers or unicode!
  190. return new Range( 0, _fib.getFibBase().getFcMac() - _fib.getFibBase().getFcMin(), this );
  191. }
  192. /**
  193. * Use {@link #getOldFontTable()} instead!!!
  194. * This always throws an IllegalArgumentException.
  195. *
  196. * @return nothing
  197. * @throws UnsupportedOperationException
  198. */
  199. @Override
  200. @NotImplemented
  201. public FontTable getFontTable() {
  202. throw new UnsupportedOperationException("Use getOldFontTable instead.");
  203. }
  204. public OldFontTable getOldFontTable() {
  205. return fontTable;
  206. }
  207. public Range getRange()
  208. {
  209. return getOverallRange();
  210. }
  211. public TextPieceTable getTextTable()
  212. {
  213. return tpt;
  214. }
  215. @Override
  216. public StringBuilder getText()
  217. {
  218. return _text;
  219. }
  220. @Override
  221. public void write() throws IOException {
  222. throw new IllegalStateException("Writing is not available for the older file formats");
  223. }
  224. @Override
  225. public void write(File out) throws IOException {
  226. throw new IllegalStateException("Writing is not available for the older file formats");
  227. }
  228. @Override
  229. public void write(OutputStream out) throws IOException {
  230. throw new IllegalStateException("Writing is not available for the older file formats");
  231. }
  232. /**
  233. * As a rough heuristic (total hack), read through the HPSF,
  234. * then read through the font table, and take the first
  235. * non-default, non-ansi, non-symbol
  236. * font's charset and return that.
  237. *
  238. * Once we figure out how to link a font to a text piece, we should
  239. * use the font information per text piece.
  240. *
  241. * @return charset
  242. */
  243. public Charset getGuessedCharset() {
  244. return guessedCharset;
  245. }
  246. }