PageRenderTime 69ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/src/org/apache/poi/hwpf/converter/AbstractWordConverter.java

https://github.com/minstrelsy/SimpleAndroidDocView
Java | 1218 lines | 1012 code | 158 blank | 48 comment | 192 complexity | a222c0be0731737a174a7721c959c7e2 MD5 | raw file
Possible License(s): Apache-2.0
  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.converter;
  16. import java.util.ArrayList;
  17. import java.util.Collections;
  18. import java.util.Iterator;
  19. import java.util.LinkedHashSet;
  20. import java.util.LinkedList;
  21. import java.util.List;
  22. import java.util.Map;
  23. import java.util.Set;
  24. import java.util.regex.Matcher;
  25. import java.util.regex.Pattern;
  26. import org.apache.poi.hpsf.SummaryInformation;
  27. import org.apache.poi.hwpf.HWPFDocument;
  28. import org.apache.poi.hwpf.HWPFDocumentCore;
  29. import org.apache.poi.hwpf.converter.AbstractWordUtils.NumberingState;
  30. import org.apache.poi.hwpf.converter.FontReplacer.Triplet;
  31. import org.apache.poi.hwpf.model.FieldsDocumentPart;
  32. import org.apache.poi.hwpf.usermodel.Bookmark;
  33. import org.apache.poi.hwpf.usermodel.CharacterRun;
  34. import org.apache.poi.hwpf.usermodel.Field;
  35. import org.apache.poi.hwpf.usermodel.HWPFList;
  36. import org.apache.poi.hwpf.usermodel.Notes;
  37. import org.apache.poi.hwpf.usermodel.OfficeDrawing;
  38. import org.apache.poi.hwpf.usermodel.Paragraph;
  39. import org.apache.poi.hwpf.usermodel.Picture;
  40. import org.apache.poi.hwpf.usermodel.PictureType;
  41. import org.apache.poi.hwpf.usermodel.Range;
  42. import org.apache.poi.hwpf.usermodel.Section;
  43. import org.apache.poi.hwpf.usermodel.Table;
  44. import org.apache.poi.hwpf.usermodel.TableCell;
  45. import org.apache.poi.hwpf.usermodel.TableRow;
  46. import org.apache.poi.poifs.filesystem.Entry;
  47. import org.apache.poi.util.Beta;
  48. import org.apache.poi.util.Internal;
  49. import org.apache.poi.util.POILogFactory;
  50. import org.apache.poi.util.POILogger;
  51. import org.w3c.dom.Document;
  52. import org.w3c.dom.Element;
  53. @Beta
  54. public abstract class AbstractWordConverter
  55. {
  56. private static class DeadFieldBoundaries
  57. {
  58. final int beginMark;
  59. final int endMark;
  60. final int separatorMark;
  61. public DeadFieldBoundaries( int beginMark, int separatorMark,
  62. int endMark )
  63. {
  64. this.beginMark = beginMark;
  65. this.separatorMark = separatorMark;
  66. this.endMark = endMark;
  67. }
  68. }
  69. private static final class Structure implements Comparable<Structure>
  70. {
  71. final int end;
  72. final int start;
  73. final Object structure;
  74. Structure( Bookmark bookmark )
  75. {
  76. this.start = bookmark.getStart();
  77. this.end = bookmark.getEnd();
  78. this.structure = bookmark;
  79. }
  80. Structure( DeadFieldBoundaries deadFieldBoundaries, int start, int end )
  81. {
  82. this.start = start;
  83. this.end = end;
  84. this.structure = deadFieldBoundaries;
  85. }
  86. Structure( Field field )
  87. {
  88. this.start = field.getFieldStartOffset();
  89. this.end = field.getFieldEndOffset();
  90. this.structure = field;
  91. }
  92. public int compareTo( Structure o )
  93. {
  94. return start < o.start ? -1 : start == o.start ? 0 : 1;
  95. }
  96. @Override
  97. public String toString()
  98. {
  99. return "Structure [" + start + "; " + end + "): "
  100. + structure.toString();
  101. }
  102. }
  103. private static final byte BEL_MARK = 7;
  104. private static final byte FIELD_BEGIN_MARK = 19;
  105. private static final byte FIELD_END_MARK = 21;
  106. private static final byte FIELD_SEPARATOR_MARK = 20;
  107. private static final POILogger logger = POILogFactory
  108. .getLogger( AbstractWordConverter.class );
  109. private static final Pattern PATTERN_HYPERLINK_EXTERNAL = Pattern
  110. .compile( "^[ \\t\\r\\n]*HYPERLINK \"(.*)\".*$" );
  111. private static final Pattern PATTERN_HYPERLINK_LOCAL = Pattern
  112. .compile( "^[ \\t\\r\\n]*HYPERLINK \\\\l \"(.*)\"[ ](.*)$" );
  113. private static final Pattern PATTERN_PAGEREF = Pattern
  114. .compile( "^[ \\t\\r\\n]*PAGEREF ([^ ]*)[ \\t\\r\\n]*\\\\h.*$" );
  115. private static final byte SPECCHAR_AUTONUMBERED_FOOTNOTE_REFERENCE = 2;
  116. private static final byte SPECCHAR_DRAWN_OBJECT = 8;
  117. protected static final char UNICODECHAR_NO_BREAK_SPACE = '\u00a0';
  118. protected static final char UNICODECHAR_NONBREAKING_HYPHEN = '\u2011';
  119. protected static final char UNICODECHAR_ZERO_WIDTH_SPACE = '\u200b';
  120. private static void addToStructures( List<Structure> structures,
  121. Structure structure )
  122. {
  123. for ( Iterator<Structure> iterator = structures.iterator(); iterator
  124. .hasNext(); )
  125. {
  126. Structure another = iterator.next();
  127. if ( another.start <= structure.start
  128. && another.end >= structure.start )
  129. {
  130. return;
  131. }
  132. if ( ( structure.start < another.start && another.start < structure.end )
  133. || ( structure.start < another.start && another.end <= structure.end )
  134. || ( structure.start <= another.start && another.end < structure.end ) )
  135. {
  136. iterator.remove();
  137. continue;
  138. }
  139. }
  140. structures.add( structure );
  141. }
  142. private final Set<Bookmark> bookmarkStack = new LinkedHashSet<Bookmark>();
  143. private FontReplacer fontReplacer = new DefaultFontReplacer();
  144. private POILogger log = POILogFactory.getLogger( getClass() );
  145. private NumberingState numberingState = new NumberingState();
  146. private PicturesManager picturesManager;
  147. /**
  148. * Special actions that need to be called after processing complete, like
  149. * updating stylesheets or building document notes list. Usually they are
  150. * called once, but it's okay to call them several times.
  151. */
  152. protected void afterProcess()
  153. {
  154. // by default no such actions needed
  155. }
  156. protected Triplet getCharacterRunTriplet( CharacterRun characterRun )
  157. {
  158. Triplet original = new Triplet();
  159. original.bold = characterRun.isBold();
  160. original.italic = characterRun.isItalic();
  161. original.fontName = characterRun.getFontName();
  162. Triplet updated = getFontReplacer().update( original );
  163. return updated;
  164. }
  165. public abstract Document getDocument();
  166. public FontReplacer getFontReplacer()
  167. {
  168. return fontReplacer;
  169. }
  170. protected int getNumberColumnsSpanned( int[] tableCellEdges,
  171. int currentEdgeIndex, TableCell tableCell )
  172. {
  173. int nextEdgeIndex = currentEdgeIndex;
  174. int colSpan = 0;
  175. int cellRightEdge = tableCell.getLeftEdge() + tableCell.getWidth();
  176. while ( tableCellEdges[nextEdgeIndex] < cellRightEdge )
  177. {
  178. colSpan++;
  179. nextEdgeIndex++;
  180. }
  181. return colSpan;
  182. }
  183. protected int getNumberRowsSpanned( Table table,
  184. final int[] tableCellEdges, int currentRowIndex,
  185. int currentColumnIndex, TableCell tableCell )
  186. {
  187. if ( !tableCell.isFirstVerticallyMerged() )
  188. return 1;
  189. final int numRows = table.numRows();
  190. int count = 1;
  191. for ( int r1 = currentRowIndex + 1; r1 < numRows; r1++ )
  192. {
  193. TableRow nextRow = table.getRow( r1 );
  194. if ( currentColumnIndex >= nextRow.numCells() )
  195. break;
  196. // we need to skip row if he don't have cells at all
  197. boolean hasCells = false;
  198. int currentEdgeIndex = 0;
  199. for ( int c = 0; c < nextRow.numCells(); c++ )
  200. {
  201. TableCell nextTableCell = nextRow.getCell( c );
  202. if ( !nextTableCell.isVerticallyMerged()
  203. || nextTableCell.isFirstVerticallyMerged() )
  204. {
  205. int colSpan = getNumberColumnsSpanned( tableCellEdges,
  206. currentEdgeIndex, nextTableCell );
  207. currentEdgeIndex += colSpan;
  208. if ( colSpan != 0 )
  209. {
  210. hasCells = true;
  211. break;
  212. }
  213. }
  214. else
  215. {
  216. currentEdgeIndex += getNumberColumnsSpanned(
  217. tableCellEdges, currentEdgeIndex, nextTableCell );
  218. }
  219. }
  220. if ( !hasCells )
  221. continue;
  222. TableCell nextCell = nextRow.getCell( currentColumnIndex );
  223. if ( !nextCell.isVerticallyMerged()
  224. || nextCell.isFirstVerticallyMerged() )
  225. break;
  226. count++;
  227. }
  228. return count;
  229. }
  230. public PicturesManager getPicturesManager()
  231. {
  232. return picturesManager;
  233. }
  234. protected abstract void outputCharacters( Element block,
  235. CharacterRun characterRun, String text );
  236. /**
  237. * Wrap range into bookmark(s) and process it. All bookmarks have starts
  238. * equal to range start and ends equal to range end. Usually it's only one
  239. * bookmark.
  240. */
  241. protected abstract void processBookmarks( HWPFDocumentCore wordDocument,
  242. Element currentBlock, Range range, int currentTableLevel,
  243. List<Bookmark> rangeBookmarks );
  244. protected boolean processCharacters( final HWPFDocumentCore wordDocument,
  245. final int currentTableLevel, final Range range, final Element block )
  246. {
  247. if ( range == null )
  248. return false;
  249. boolean haveAnyText = false;
  250. /*
  251. * In text there can be fields, bookmarks, may be other structures (code
  252. * below allows extension). Those structures can overlaps, so either we
  253. * should process char-by-char (slow) or find a correct way to
  254. * reconstruct the structure of range -- sergey
  255. */
  256. List<Structure> structures = new LinkedList<Structure>();
  257. if ( wordDocument instanceof HWPFDocument )
  258. {
  259. final HWPFDocument doc = (HWPFDocument) wordDocument;
  260. Map<Integer, List<Bookmark>> rangeBookmarks = doc.getBookmarks()
  261. .getBookmarksStartedBetween( range.getStartOffset(),
  262. range.getEndOffset() );
  263. if ( rangeBookmarks != null )
  264. {
  265. for ( List<Bookmark> lists : rangeBookmarks.values() )
  266. {
  267. for ( Bookmark bookmark : lists )
  268. {
  269. if ( !bookmarkStack.contains( bookmark ) )
  270. addToStructures( structures, new Structure(
  271. bookmark ) );
  272. }
  273. }
  274. }
  275. // TODO: dead fields?
  276. int skipUntil = -1;
  277. for ( int c = 0; c < range.numCharacterRuns(); c++ )
  278. {
  279. CharacterRun characterRun = range.getCharacterRun( c );
  280. if ( characterRun == null )
  281. throw new AssertionError();
  282. if ( characterRun.getStartOffset() < skipUntil )
  283. continue;
  284. String text = characterRun.text();
  285. if ( text == null || text.length() == 0
  286. || text.charAt( 0 ) != FIELD_BEGIN_MARK )
  287. continue;
  288. Field aliveField = ( (HWPFDocument) wordDocument ).getFields()
  289. .getFieldByStartOffset( FieldsDocumentPart.MAIN,
  290. characterRun.getStartOffset() );
  291. if ( aliveField != null )
  292. {
  293. addToStructures( structures, new Structure( aliveField ) );
  294. }
  295. else
  296. {
  297. int[] separatorEnd = tryDeadField_lookupFieldSeparatorEnd(
  298. wordDocument, range, c );
  299. if ( separatorEnd != null )
  300. {
  301. addToStructures(
  302. structures,
  303. new Structure( new DeadFieldBoundaries( c,
  304. separatorEnd[0], separatorEnd[1] ),
  305. characterRun.getStartOffset(), range
  306. .getCharacterRun(
  307. separatorEnd[1] )
  308. .getEndOffset() ) );
  309. c = separatorEnd[1];
  310. }
  311. }
  312. }
  313. }
  314. structures = new ArrayList<Structure>( structures );
  315. Collections.sort( structures );
  316. int previous = range.getStartOffset();
  317. for ( Structure structure : structures )
  318. {
  319. if ( structure.start != previous )
  320. {
  321. Range subrange = new Range( previous, structure.start, range )
  322. {
  323. @Override
  324. public String toString()
  325. {
  326. return "BetweenStructuresSubrange " + super.toString();
  327. }
  328. };
  329. processCharacters( wordDocument, currentTableLevel, subrange,
  330. block );
  331. }
  332. if ( structure.structure instanceof Bookmark )
  333. {
  334. // other bookmarks with same boundaries
  335. List<Bookmark> bookmarks = new LinkedList<Bookmark>();
  336. for ( Bookmark bookmark : ( (HWPFDocument) wordDocument )
  337. .getBookmarks()
  338. .getBookmarksStartedBetween( structure.start,
  339. structure.start + 1 ).values().iterator()
  340. .next() )
  341. {
  342. if ( bookmark.getStart() == structure.start
  343. && bookmark.getEnd() == structure.end )
  344. {
  345. bookmarks.add( bookmark );
  346. }
  347. }
  348. bookmarkStack.addAll( bookmarks );
  349. try
  350. {
  351. int end = Math.min( range.getEndOffset(), structure.end );
  352. Range subrange = new Range( structure.start, end, range )
  353. {
  354. @Override
  355. public String toString()
  356. {
  357. return "BookmarksSubrange " + super.toString();
  358. }
  359. };
  360. processBookmarks( wordDocument, block, subrange,
  361. currentTableLevel, bookmarks );
  362. }
  363. finally
  364. {
  365. bookmarkStack.removeAll( bookmarks );
  366. }
  367. }
  368. else if ( structure.structure instanceof Field )
  369. {
  370. Field field = (Field) structure.structure;
  371. processField( (HWPFDocument) wordDocument, range,
  372. currentTableLevel, field, block );
  373. }
  374. else if ( structure.structure instanceof DeadFieldBoundaries )
  375. {
  376. DeadFieldBoundaries boundaries = (DeadFieldBoundaries) structure.structure;
  377. processDeadField( wordDocument, block, range,
  378. currentTableLevel, boundaries.beginMark,
  379. boundaries.separatorMark, boundaries.endMark );
  380. }
  381. else
  382. {
  383. throw new UnsupportedOperationException( "NYI: "
  384. + structure.structure.getClass() );
  385. }
  386. previous = Math.min( range.getEndOffset(), structure.end );
  387. }
  388. if ( previous != range.getStartOffset() )
  389. {
  390. if ( previous > range.getEndOffset() )
  391. {
  392. logger.log( POILogger.WARN, "Latest structure in ", range,
  393. " ended at #" + previous, " after range boundaries [",
  394. range.getStartOffset() + "; " + range.getEndOffset(),
  395. ")" );
  396. return true;
  397. }
  398. if ( previous < range.getEndOffset() )
  399. {
  400. Range subrange = new Range( previous, range.getEndOffset(),
  401. range )
  402. {
  403. @Override
  404. public String toString()
  405. {
  406. return "AfterStructureSubrange " + super.toString();
  407. }
  408. };
  409. processCharacters( wordDocument, currentTableLevel, subrange,
  410. block );
  411. }
  412. return true;
  413. }
  414. for ( int c = 0; c < range.numCharacterRuns(); c++ )
  415. {
  416. CharacterRun characterRun = range.getCharacterRun( c );
  417. if ( characterRun == null )
  418. throw new AssertionError();
  419. if ( wordDocument instanceof HWPFDocument
  420. && ( (HWPFDocument) wordDocument ).getPicturesTable()
  421. .hasPicture( characterRun ) )
  422. {
  423. HWPFDocument newFormat = (HWPFDocument) wordDocument;
  424. Picture picture = newFormat.getPicturesTable().extractPicture(
  425. characterRun, true );
  426. processImage( block, characterRun.text().charAt( 0 ) == 0x01,
  427. picture );
  428. continue;
  429. }
  430. String text = characterRun.text();
  431. if ( text.getBytes().length == 0 )
  432. continue;
  433. if ( characterRun.isSpecialCharacter() )
  434. {
  435. if ( text.charAt( 0 ) == SPECCHAR_AUTONUMBERED_FOOTNOTE_REFERENCE
  436. && ( wordDocument instanceof HWPFDocument ) )
  437. {
  438. HWPFDocument doc = (HWPFDocument) wordDocument;
  439. processNoteAnchor( doc, characterRun, block );
  440. continue;
  441. }
  442. if ( text.charAt( 0 ) == SPECCHAR_DRAWN_OBJECT
  443. && ( wordDocument instanceof HWPFDocument ) )
  444. {
  445. HWPFDocument doc = (HWPFDocument) wordDocument;
  446. processDrawnObject( doc, characterRun, block );
  447. continue;
  448. }
  449. if ( characterRun.isOle2()
  450. && ( wordDocument instanceof HWPFDocument ) )
  451. {
  452. HWPFDocument doc = (HWPFDocument) wordDocument;
  453. processOle2( doc, characterRun, block );
  454. continue;
  455. }
  456. if ( characterRun.isSymbol()
  457. && ( wordDocument instanceof HWPFDocument ) )
  458. {
  459. HWPFDocument doc = (HWPFDocument) wordDocument;
  460. processSymbol( doc, characterRun, block );
  461. continue;
  462. }
  463. }
  464. if ( text.getBytes()[0] == FIELD_BEGIN_MARK )
  465. {
  466. if ( wordDocument instanceof HWPFDocument )
  467. {
  468. Field aliveField = ( (HWPFDocument) wordDocument )
  469. .getFields().getFieldByStartOffset(
  470. FieldsDocumentPart.MAIN,
  471. characterRun.getStartOffset() );
  472. if ( aliveField != null )
  473. {
  474. processField( ( (HWPFDocument) wordDocument ), range,
  475. currentTableLevel, aliveField, block );
  476. int continueAfter = aliveField.getFieldEndOffset();
  477. while ( c < range.numCharacterRuns()
  478. && range.getCharacterRun( c ).getEndOffset() <= continueAfter )
  479. c++;
  480. if ( c < range.numCharacterRuns() )
  481. c--;
  482. continue;
  483. }
  484. }
  485. int skipTo = tryDeadField( wordDocument, range,
  486. currentTableLevel, c, block );
  487. if ( skipTo != c )
  488. {
  489. c = skipTo;
  490. continue;
  491. }
  492. continue;
  493. }
  494. if ( text.getBytes()[0] == FIELD_SEPARATOR_MARK )
  495. {
  496. // shall not appear without FIELD_BEGIN_MARK
  497. continue;
  498. }
  499. if ( text.getBytes()[0] == FIELD_END_MARK )
  500. {
  501. // shall not appear without FIELD_BEGIN_MARK
  502. continue;
  503. }
  504. if ( characterRun.isSpecialCharacter() || characterRun.isObj()
  505. || characterRun.isOle2() )
  506. {
  507. continue;
  508. }
  509. if ( text.endsWith( "\r" )
  510. || ( text.charAt( text.length() - 1 ) == BEL_MARK && currentTableLevel != Integer.MIN_VALUE ) )
  511. text = text.substring( 0, text.length() - 1 );
  512. {
  513. // line breaks
  514. StringBuilder stringBuilder = new StringBuilder();
  515. for ( char charChar : text.toCharArray() )
  516. {
  517. if ( charChar == 11 )
  518. {
  519. if ( stringBuilder.length() > 0 )
  520. {
  521. outputCharacters( block, characterRun,
  522. stringBuilder.toString() );
  523. stringBuilder.setLength( 0 );
  524. }
  525. processLineBreak( block, characterRun );
  526. }
  527. else if ( charChar == 30 )
  528. {
  529. // Non-breaking hyphens are stored as ASCII 30
  530. stringBuilder.append( UNICODECHAR_NONBREAKING_HYPHEN );
  531. }
  532. else if ( charChar == 31 )
  533. {
  534. // Non-required hyphens to zero-width space
  535. stringBuilder.append( UNICODECHAR_ZERO_WIDTH_SPACE );
  536. }
  537. else if ( charChar >= 0x20 || charChar == 0x09
  538. || charChar == 0x0A || charChar == 0x0D )
  539. {
  540. stringBuilder.append( charChar );
  541. }
  542. }
  543. if ( stringBuilder.length() > 0 )
  544. {
  545. outputCharacters( block, characterRun,
  546. stringBuilder.toString() );
  547. stringBuilder.setLength( 0 );
  548. }
  549. }
  550. haveAnyText |= text.trim().length() != 0;
  551. }
  552. return haveAnyText;
  553. }
  554. protected void processDeadField( HWPFDocumentCore wordDocument,
  555. Element currentBlock, Range range, int currentTableLevel,
  556. int beginMark, int separatorMark, int endMark )
  557. {
  558. if ( beginMark + 1 < separatorMark && separatorMark + 1 < endMark )
  559. {
  560. Range formulaRange = new Range( range.getCharacterRun(
  561. beginMark + 1 ).getStartOffset(), range.getCharacterRun(
  562. separatorMark - 1 ).getEndOffset(), range )
  563. {
  564. @Override
  565. public String toString()
  566. {
  567. return "Dead field formula subrange: " + super.toString();
  568. }
  569. };
  570. Range valueRange = new Range( range.getCharacterRun(
  571. separatorMark + 1 ).getStartOffset(), range
  572. .getCharacterRun( endMark - 1 ).getEndOffset(), range )
  573. {
  574. @Override
  575. public String toString()
  576. {
  577. return "Dead field value subrange: " + super.toString();
  578. }
  579. };
  580. String formula = formulaRange.text();
  581. final Matcher matcher = PATTERN_HYPERLINK_LOCAL.matcher( formula );
  582. if ( matcher.matches() )
  583. {
  584. String localref = matcher.group( 1 );
  585. processPageref( wordDocument, currentBlock, valueRange,
  586. currentTableLevel, localref );
  587. return;
  588. }
  589. }
  590. StringBuilder debug = new StringBuilder( "Unsupported field type: \n" );
  591. for ( int i = beginMark; i <= endMark; i++ )
  592. {
  593. debug.append( "\t" );
  594. debug.append( range.getCharacterRun( i ) );
  595. debug.append( "\n" );
  596. }
  597. logger.log( POILogger.WARN, debug );
  598. Range deadFieldValueSubrage = new Range( range.getCharacterRun(
  599. separatorMark ).getStartOffset() + 1, range.getCharacterRun(
  600. endMark ).getStartOffset(), range )
  601. {
  602. @Override
  603. public String toString()
  604. {
  605. return "DeadFieldValueSubrange (" + super.toString() + ")";
  606. }
  607. };
  608. // just output field value
  609. if ( separatorMark + 1 < endMark )
  610. processCharacters( wordDocument, currentTableLevel,
  611. deadFieldValueSubrage, currentBlock );
  612. return;
  613. }
  614. public void processDocument( HWPFDocumentCore wordDocument )
  615. {
  616. try
  617. {
  618. final SummaryInformation summaryInformation = wordDocument
  619. .getSummaryInformation();
  620. if ( summaryInformation != null )
  621. {
  622. processDocumentInformation( summaryInformation );
  623. }
  624. }
  625. catch ( Exception exc )
  626. {
  627. logger.log( POILogger.WARN,
  628. "Unable to process document summary information: ", exc,
  629. exc );
  630. }
  631. final Range docRange = wordDocument.getRange();
  632. if ( docRange.numSections() == 1 )
  633. {
  634. processSingleSection( wordDocument, docRange.getSection( 0 ) );
  635. afterProcess();
  636. return;
  637. }
  638. processDocumentPart( wordDocument, docRange );
  639. afterProcess();
  640. }
  641. protected abstract void processDocumentInformation(
  642. SummaryInformation summaryInformation );
  643. protected void processDocumentPart( HWPFDocumentCore wordDocument,
  644. final Range range )
  645. {
  646. for ( int s = 0; s < range.numSections(); s++ )
  647. {
  648. processSection( wordDocument, range.getSection( s ), s );
  649. }
  650. }
  651. protected void processDrawnObject( HWPFDocument doc,
  652. CharacterRun characterRun, Element block )
  653. {
  654. if ( getPicturesManager() == null )
  655. return;
  656. // TODO: support headers
  657. OfficeDrawing officeDrawing = doc.getOfficeDrawingsMain()
  658. .getOfficeDrawingAt( characterRun.getStartOffset() );
  659. if ( officeDrawing == null )
  660. {
  661. logger.log( POILogger.WARN, "Characters #" + characterRun
  662. + " references missing drawn object" );
  663. return;
  664. }
  665. byte[] pictureData = officeDrawing.getPictureData();
  666. if ( pictureData == null )
  667. // usual shape?
  668. return;
  669. float width = ( officeDrawing.getRectangleRight() - officeDrawing
  670. .getRectangleLeft() ) / AbstractWordUtils.TWIPS_PER_INCH;
  671. float height = ( officeDrawing.getRectangleBottom() - officeDrawing
  672. .getRectangleTop() ) / AbstractWordUtils.TWIPS_PER_INCH;
  673. final PictureType type = PictureType.findMatchingType( pictureData );
  674. String path = getPicturesManager()
  675. .savePicture( pictureData, type,
  676. "s" + characterRun.getStartOffset() + "." + type,
  677. width, height );
  678. processDrawnObject( doc, characterRun, officeDrawing, path, block );
  679. }
  680. protected abstract void processDrawnObject( HWPFDocument doc,
  681. CharacterRun characterRun, OfficeDrawing officeDrawing,
  682. String path, Element block );
  683. protected void processDropDownList( Element block,
  684. CharacterRun characterRun, String[] values, int defaultIndex )
  685. {
  686. outputCharacters( block, characterRun, values[defaultIndex] );
  687. }
  688. protected abstract void processEndnoteAutonumbered(
  689. HWPFDocument wordDocument, int noteIndex, Element block,
  690. Range endnoteTextRange );
  691. protected void processField( HWPFDocument wordDocument, Range parentRange,
  692. int currentTableLevel, Field field, Element currentBlock )
  693. {
  694. switch ( field.getType() )
  695. {
  696. case 37: // page reference
  697. {
  698. final Range firstSubrange = field.firstSubrange( parentRange );
  699. if ( firstSubrange != null )
  700. {
  701. String formula = firstSubrange.text();
  702. Matcher matcher = PATTERN_PAGEREF.matcher( formula );
  703. if ( matcher.find() )
  704. {
  705. String pageref = matcher.group( 1 );
  706. processPageref( wordDocument, currentBlock,
  707. field.secondSubrange( parentRange ),
  708. currentTableLevel, pageref );
  709. return;
  710. }
  711. }
  712. break;
  713. }
  714. case 58: // Embedded Object
  715. {
  716. if ( !field.hasSeparator() )
  717. {
  718. logger.log( POILogger.WARN, parentRange + " contains " + field
  719. + " with 'Embedded Object' but without separator mark" );
  720. return;
  721. }
  722. CharacterRun separator = field
  723. .getMarkSeparatorCharacterRun( parentRange );
  724. if ( separator.isOle2() )
  725. {
  726. // the only supported so far
  727. boolean processed = processOle2( wordDocument, separator,
  728. currentBlock );
  729. // if we didn't output OLE - output field value
  730. if ( !processed )
  731. {
  732. processCharacters( wordDocument, currentTableLevel,
  733. field.secondSubrange( parentRange ), currentBlock );
  734. }
  735. return;
  736. }
  737. break;
  738. }
  739. case 83: // drop down
  740. {
  741. Range fieldContent = field.firstSubrange( parentRange );
  742. CharacterRun cr = fieldContent.getCharacterRun( fieldContent
  743. .numCharacterRuns() - 1 );
  744. String[] values = cr.getDropDownListValues();
  745. Integer defIndex = cr.getDropDownListDefaultItemIndex();
  746. if ( values != null )
  747. {
  748. processDropDownList( currentBlock, cr, values,
  749. defIndex == null ? -1 : defIndex.intValue() );
  750. return;
  751. }
  752. break;
  753. }
  754. case 88: // hyperlink
  755. {
  756. final Range firstSubrange = field.firstSubrange( parentRange );
  757. if ( firstSubrange != null )
  758. {
  759. String formula = firstSubrange.text();
  760. Matcher matcher = PATTERN_HYPERLINK_EXTERNAL.matcher( formula );
  761. if ( matcher.matches() )
  762. {
  763. String hyperlink = matcher.group( 1 );
  764. processHyperlink( wordDocument, currentBlock,
  765. field.secondSubrange( parentRange ),
  766. currentTableLevel, hyperlink );
  767. return;
  768. }
  769. matcher.usePattern( PATTERN_HYPERLINK_LOCAL );
  770. if ( matcher.matches() )
  771. {
  772. String hyperlink = matcher.group( 1 );
  773. Range textRange = null;
  774. String text = matcher.group( 2 );
  775. if ( AbstractWordUtils.isNotEmpty( text ) )
  776. {
  777. textRange = new Range( firstSubrange.getStartOffset()
  778. + matcher.start( 2 ),
  779. firstSubrange.getStartOffset()
  780. + matcher.end( 2 ), firstSubrange )
  781. {
  782. @Override
  783. public String toString()
  784. {
  785. return "Local hyperlink text";
  786. }
  787. };
  788. }
  789. processPageref( wordDocument, currentBlock, textRange,
  790. currentTableLevel, hyperlink );
  791. return;
  792. }
  793. }
  794. break;
  795. }
  796. }
  797. logger.log( POILogger.WARN, parentRange + " contains " + field
  798. + " with unsupported type or format" );
  799. processCharacters( wordDocument, currentTableLevel,
  800. field.secondSubrange( parentRange ), currentBlock );
  801. }
  802. protected abstract void processFootnoteAutonumbered(
  803. HWPFDocument wordDocument, int noteIndex, Element block,
  804. Range footnoteTextRange );
  805. protected abstract void processHyperlink( HWPFDocumentCore wordDocument,
  806. Element currentBlock, Range textRange, int currentTableLevel,
  807. String hyperlink );
  808. protected void processImage( Element currentBlock, boolean inlined,
  809. Picture picture )
  810. {
  811. PicturesManager fileManager = getPicturesManager();
  812. if ( fileManager != null )
  813. {
  814. final int aspectRatioX = picture.getHorizontalScalingFactor();
  815. final int aspectRatioY = picture.getVerticalScalingFactor();
  816. final float imageWidth = aspectRatioX > 0 ? picture.getDxaGoal()
  817. * aspectRatioX / 1000 / AbstractWordUtils.TWIPS_PER_INCH
  818. : picture.getDxaGoal() / AbstractWordUtils.TWIPS_PER_INCH;
  819. final float imageHeight = aspectRatioY > 0 ? picture.getDyaGoal()
  820. * aspectRatioY / 1000 / AbstractWordUtils.TWIPS_PER_INCH
  821. : picture.getDyaGoal() / AbstractWordUtils.TWIPS_PER_INCH;
  822. String url = fileManager.savePicture( picture.getContent(),
  823. picture.suggestPictureType(),
  824. picture.suggestFullFileName(), imageWidth, imageHeight );
  825. if ( WordToFoUtils.isNotEmpty( url ) )
  826. {
  827. processImage( currentBlock, inlined, picture, url );
  828. return;
  829. }
  830. }
  831. processImageWithoutPicturesManager( currentBlock, inlined, picture );
  832. }
  833. protected abstract void processImage( Element currentBlock,
  834. boolean inlined, Picture picture, String url );
  835. @Internal
  836. protected abstract void processImageWithoutPicturesManager(
  837. Element currentBlock, boolean inlined, Picture picture );
  838. protected abstract void processLineBreak( Element block,
  839. CharacterRun characterRun );
  840. protected void processNoteAnchor( HWPFDocument doc,
  841. CharacterRun characterRun, final Element block )
  842. {
  843. {
  844. Notes footnotes = doc.getFootnotes();
  845. int noteIndex = footnotes
  846. .getNoteIndexByAnchorPosition( characterRun
  847. .getStartOffset() );
  848. if ( noteIndex != -1 )
  849. {
  850. Range footnoteRange = doc.getFootnoteRange();
  851. int rangeStartOffset = footnoteRange.getStartOffset();
  852. int noteTextStartOffset = footnotes
  853. .getNoteTextStartOffset( noteIndex );
  854. int noteTextEndOffset = footnotes
  855. .getNoteTextEndOffset( noteIndex );
  856. Range noteTextRange = new Range( rangeStartOffset
  857. + noteTextStartOffset, rangeStartOffset
  858. + noteTextEndOffset, doc );
  859. processFootnoteAutonumbered( doc, noteIndex, block,
  860. noteTextRange );
  861. return;
  862. }
  863. }
  864. {
  865. Notes endnotes = doc.getEndnotes();
  866. int noteIndex = endnotes.getNoteIndexByAnchorPosition( characterRun
  867. .getStartOffset() );
  868. if ( noteIndex != -1 )
  869. {
  870. Range endnoteRange = doc.getEndnoteRange();
  871. int rangeStartOffset = endnoteRange.getStartOffset();
  872. int noteTextStartOffset = endnotes
  873. .getNoteTextStartOffset( noteIndex );
  874. int noteTextEndOffset = endnotes
  875. .getNoteTextEndOffset( noteIndex );
  876. Range noteTextRange = new Range( rangeStartOffset
  877. + noteTextStartOffset, rangeStartOffset
  878. + noteTextEndOffset, doc );
  879. processEndnoteAutonumbered( doc, noteIndex, block,
  880. noteTextRange );
  881. return;
  882. }
  883. }
  884. }
  885. private boolean processOle2( HWPFDocument doc, CharacterRun characterRun,
  886. Element block )
  887. {
  888. Entry entry = doc.getObjectsPool().getObjectById(
  889. "_" + characterRun.getPicOffset() );
  890. if ( entry == null )
  891. {
  892. logger.log( POILogger.WARN, "Referenced OLE2 object '",
  893. Integer.valueOf( characterRun.getPicOffset() ),
  894. "' not found in ObjectPool" );
  895. return false;
  896. }
  897. try
  898. {
  899. return processOle2( doc, block, entry );
  900. }
  901. catch ( Exception exc )
  902. {
  903. logger.log( POILogger.WARN,
  904. "Unable to convert internal OLE2 object '",
  905. Integer.valueOf( characterRun.getPicOffset() ), "': ", exc,
  906. exc );
  907. return false;
  908. }
  909. }
  910. @SuppressWarnings( "unused" )
  911. protected boolean processOle2( HWPFDocument wordDocument, Element block,
  912. Entry entry ) throws Exception
  913. {
  914. return false;
  915. }
  916. protected abstract void processPageBreak( HWPFDocumentCore wordDocument,
  917. Element flow );
  918. protected abstract void processPageref( HWPFDocumentCore wordDocument,
  919. Element currentBlock, Range textRange, int currentTableLevel,
  920. String pageref );
  921. protected abstract void processParagraph( HWPFDocumentCore wordDocument,
  922. Element parentElement, int currentTableLevel, Paragraph paragraph,
  923. String bulletText );
  924. protected void processParagraphes( HWPFDocumentCore wordDocument,
  925. Element flow, Range range, int currentTableLevel )
  926. {
  927. final int paragraphs = range.numParagraphs();
  928. for ( int p = 0; p < paragraphs; p++ )
  929. {
  930. Paragraph paragraph = range.getParagraph( p );
  931. if ( paragraph.isInTable()
  932. && paragraph.getTableLevel() != currentTableLevel )
  933. {
  934. if ( paragraph.getTableLevel() < currentTableLevel )
  935. throw new IllegalStateException(
  936. "Trying to process table cell with higher level ("
  937. + paragraph.getTableLevel()
  938. + ") than current table level ("
  939. + currentTableLevel
  940. + ") as inner table part" );
  941. Table table = range.getTable( paragraph );
  942. processTable( wordDocument, flow, table );
  943. p += table.numParagraphs();
  944. p--;
  945. continue;
  946. }
  947. if ( paragraph.text().equals( "\u000c" ) )
  948. {
  949. processPageBreak( wordDocument, flow );
  950. }
  951. boolean processed = false;
  952. if ( paragraph.isInList() )
  953. {
  954. try
  955. {
  956. HWPFList hwpfList = paragraph.getList();
  957. String label = AbstractWordUtils.getBulletText(
  958. numberingState, hwpfList,
  959. (char) paragraph.getIlvl() );
  960. processParagraph( wordDocument, flow, currentTableLevel,
  961. paragraph, label );
  962. processed = true;
  963. }
  964. catch ( Exception exc )
  965. {
  966. log.log(
  967. POILogger.WARN,
  968. "Can't process paragraph as list entry, will be processed without list information",
  969. exc );
  970. }
  971. }
  972. if ( processed == false )
  973. {
  974. processParagraph( wordDocument, flow, currentTableLevel,
  975. paragraph, AbstractWordUtils.EMPTY );
  976. }
  977. }
  978. }
  979. protected abstract void processSection( HWPFDocumentCore wordDocument,
  980. Section section, int s );
  981. protected void processSingleSection( HWPFDocumentCore wordDocument,
  982. Section section )
  983. {
  984. processSection( wordDocument, section, 0 );
  985. }
  986. protected void processSymbol( HWPFDocument doc, CharacterRun characterRun,
  987. Element block )
  988. {
  989. }
  990. protected abstract void processTable( HWPFDocumentCore wordDocument,
  991. Element flow, Table table );
  992. public void setFontReplacer( FontReplacer fontReplacer )
  993. {
  994. this.fontReplacer = fontReplacer;
  995. }
  996. public void setPicturesManager( PicturesManager fileManager )
  997. {
  998. this.picturesManager = fileManager;
  999. }
  1000. protected int tryDeadField( HWPFDocumentCore wordDocument, Range range,
  1001. int currentTableLevel, int beginMark, Element currentBlock )
  1002. {
  1003. int[] separatorEnd = tryDeadField_lookupFieldSeparatorEnd(
  1004. wordDocument, range, beginMark );
  1005. if ( separatorEnd == null )
  1006. return beginMark;
  1007. processDeadField( wordDocument, currentBlock, range, currentTableLevel,
  1008. beginMark, separatorEnd[0], separatorEnd[1] );
  1009. return separatorEnd[1];
  1010. }
  1011. private int[] tryDeadField_lookupFieldSeparatorEnd(
  1012. HWPFDocumentCore wordDocument, Range range, int beginMark )
  1013. {
  1014. int separatorMark = -1;
  1015. int endMark = -1;
  1016. for ( int c = beginMark + 1; c < range.numCharacterRuns(); c++ )
  1017. {
  1018. CharacterRun characterRun = range.getCharacterRun( c );
  1019. String text = characterRun.text();
  1020. if ( text.getBytes().length == 0 )
  1021. continue;
  1022. final byte firstByte = text.getBytes()[0];
  1023. if ( firstByte == FIELD_BEGIN_MARK )
  1024. {
  1025. int[] nested = tryDeadField_lookupFieldSeparatorEnd(
  1026. wordDocument, range, c );
  1027. if ( nested != null )
  1028. {
  1029. c = nested[1];
  1030. }
  1031. continue;
  1032. }
  1033. if ( firstByte == FIELD_SEPARATOR_MARK )
  1034. {
  1035. if ( separatorMark != -1 )
  1036. {
  1037. // double; incorrect format
  1038. return null;
  1039. }
  1040. separatorMark = c;
  1041. continue;
  1042. }
  1043. if ( text.getBytes()[0] == FIELD_END_MARK )
  1044. {
  1045. if ( endMark != -1 )
  1046. {
  1047. // double;
  1048. return null;
  1049. }
  1050. endMark = c;
  1051. break;
  1052. }
  1053. }
  1054. if ( separatorMark == -1 || endMark == -1 )
  1055. return null;
  1056. return new int[] { separatorMark, endMark };
  1057. }
  1058. }