org.apache.poi.xwpf.usermodel.XWPFHeader Java Examples

The following examples show how to use org.apache.poi.xwpf.usermodel.XWPFHeader. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ParseWord07.java    From autopoi with Apache License 2.0 6 votes vote down vote up
/**
 * 解析页眉和页脚
 * 
 * @param doc
 * @param map
 * @throws Exception
 */
private void parseHeaderAndFoot(MyXWPFDocument doc, Map<String, Object> map) throws Exception {
	List<XWPFHeader> headerList = doc.getHeaderList();
	for (XWPFHeader xwpfHeader : headerList) {
		for (int i = 0; i < xwpfHeader.getListParagraph().size(); i++) {
			parseThisParagraph(xwpfHeader.getListParagraph().get(i), map);
		}
	}
	List<XWPFFooter> footerList = doc.getFooterList();
	for (XWPFFooter xwpfFooter : footerList) {
		for (int i = 0; i < xwpfFooter.getListParagraph().size(); i++) {
			parseThisParagraph(xwpfFooter.getListParagraph().get(i), map);
		}
	}

}
 
Example #2
Source File: ParseWord07.java    From jeasypoi with Apache License 2.0 6 votes vote down vote up
/**
 * 解析页眉和页脚
 * 
 * @param doc
 * @param map
 * @throws Exception
 */
private void parseHeaderAndFoot(MyXWPFDocument doc, Map<String, Object> map) throws Exception {
	List<XWPFHeader> headerList = doc.getHeaderList();
	for (XWPFHeader xwpfHeader : headerList) {
		for (int i = 0; i < xwpfHeader.getListParagraph().size(); i++) {
			parseThisParagraph(xwpfHeader.getListParagraph().get(i), map);
		}
	}
	List<XWPFFooter> footerList = doc.getFooterList();
	for (XWPFFooter xwpfFooter : footerList) {
		for (int i = 0; i < xwpfFooter.getListParagraph().size(); i++) {
			parseThisParagraph(xwpfFooter.getListParagraph().get(i), map);
		}
	}

}
 
Example #3
Source File: ParseWord07.java    From easypoi with Apache License 2.0 6 votes vote down vote up
/**
 * 解析页眉和页脚
 * @param doc
 * @param map
 * @throws Exception
 */
private void parseHeaderAndFoot(MyXWPFDocument doc, Map<String, Object> map) throws Exception {
    List<XWPFHeader> headerList = doc.getHeaderList();
    for (XWPFHeader xwpfHeader : headerList) {
        for (int i = 0; i < xwpfHeader.getListParagraph().size(); i++) {
            parseThisParagraph(xwpfHeader.getListParagraph().get(i), map);
        }
    }
    List<XWPFFooter> footerList = doc.getFooterList();
    for (XWPFFooter xwpfFooter : footerList) {
        for (int i = 0; i < xwpfFooter.getListParagraph().size(); i++) {
            parseThisParagraph(xwpfFooter.getListParagraph().get(i), map);
        }
    }

}
 
Example #4
Source File: M2DocEvaluator.java    From M2Doc with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public XWPFParagraph caseDocumentTemplate(DocumentTemplate documentTemplate) {
    cleanBody(generatedDocument);

    final int unitOfWork = MONITOR_WORK
        / (1 + documentTemplate.getFooters().size() + documentTemplate.getHeaders().size());

    doSwitch(documentTemplate.getBody());
    worked(monitor, unitOfWork);

    final XWPFDocument document = (XWPFDocument) generatedDocument;
    final Iterator<XWPFFooter> footers = document.getFooterList().iterator();
    for (final Block footer : documentTemplate.getFooters()) {
        final XWPFFooter f = footers.next();
        cleanBody(f);
        generatedDocument = f;
        doSwitch(footer);
        worked(monitor, unitOfWork);
    }
    final Iterator<XWPFHeader> headers = document.getHeaderList().iterator();
    for (final Block header : documentTemplate.getHeaders()) {
        final XWPFHeader h = headers.next();
        cleanBody(h);
        generatedDocument = h;
        doSwitch(header);
        worked(monitor, unitOfWork);
    }

    return currentGeneratedParagraph;
}
 
Example #5
Source File: TemplateCustomProperties.java    From M2Doc with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Gets the {@link List} of missing variable names.
 * 
 * @return the {@link List} of missing variable names
 */
public List<String> getMissingVariables() {
    final List<String> res = new ArrayList<>();

    final IQueryEnvironment queryEnvironment = Query.newEnvironment();
    final M2DocParser parser = new M2DocParser(document, queryEnvironment);
    try {
        final List<Template> templates = new ArrayList<>();
        final Block block = parser.parseBlock(templates);
        final Set<String> missing = new LinkedHashSet<>();
        final Set<String> used = new LinkedHashSet<>();
        walkForNeededVariables(new ArrayList<>(getVariables().keySet()), missing, used, block);
        for (XWPFFooter footer : document.getFooterList()) {
            final M2DocParser footerParser = new M2DocParser(footer, queryEnvironment);
            final Block footerBlock = footerParser.parseBlock(null, TokenType.EOF);
            walkForNeededVariables(new ArrayList<>(getVariables().keySet()), missing, used, footerBlock);
        }
        for (XWPFHeader header : document.getHeaderList()) {
            final M2DocParser headerParser = new M2DocParser(header, queryEnvironment);
            final Block headerBlock = headerParser.parseBlock(null, TokenType.EOF);
            walkForNeededVariables(new ArrayList<>(getVariables().keySet()), missing, used, headerBlock);
        }
        res.addAll(missing);
    } catch (DocumentParserException e) {
        // can't parse then nothing is missing
    }

    return res;
}
 
Example #6
Source File: TemplateCustomProperties.java    From M2Doc with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Gets the {@link List} of unused variable names.
 * 
 * @return the {@link List} of unused variable names
 */
public List<String> getUnusedDeclarations() {
    final List<String> res = new ArrayList<>(getVariables().keySet());

    final IQueryEnvironment queryEnvironment = Query.newEnvironment();
    final M2DocParser parser = new M2DocParser(document, queryEnvironment);
    try {
        final List<Template> templates = new ArrayList<>();
        final Block block = parser.parseBlock(templates);
        final Set<String> missing = new LinkedHashSet<>();
        final Set<String> used = new LinkedHashSet<>();
        walkForNeededVariables(new ArrayList<>(getVariables().keySet()), missing, used, block);
        for (XWPFFooter footer : document.getFooterList()) {
            final M2DocParser footerParser = new M2DocParser(footer, queryEnvironment);
            final Block footerBlock = footerParser.parseBlock(null, TokenType.EOF);
            walkForNeededVariables(new ArrayList<>(getVariables().keySet()), missing, used, footerBlock);
        }
        for (XWPFHeader header : document.getHeaderList()) {
            final M2DocParser headerParser = new M2DocParser(header, queryEnvironment);
            final Block headerBlock = headerParser.parseBlock(null, TokenType.EOF);
            walkForNeededVariables(new ArrayList<>(getVariables().keySet()), missing, used, headerBlock);
        }
        res.removeAll(used);
    } catch (DocumentParserException e) {
        // can't parse then nothing is used
    }

    return res;
}
 
Example #7
Source File: POIServices.java    From M2Doc with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Marks the {@link CTSimpleField} of the given {@link IBody} as
 * {@link CTSimpleField#setDirty(org.openxmlformats.schemas.wordprocessingml.x2006.main.STOnOff.Enum) dirty}.
 * 
 * @param body
 *            the {@link IBody}
 */
public void markFieldsAsDirty(IBody body) {
    if (body instanceof XWPFDocument) {
        final XWPFDocument document = (XWPFDocument) body;
        for (XWPFHeader header : document.getHeaderList()) {
            markFieldsAsDirty(header);
        }
        for (XWPFFooter footer : document.getFooterList()) {
            markFieldsAsDirty(footer);
        }
    }
    for (IBodyElement element : body.getBodyElements()) {
        markFieldsAsDirty(element);
    }
}
 
Example #8
Source File: M2DocUtils.java    From M2Doc with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Parses a document for {@link UserContent} and returns the {@link DocumentTemplate} resulting from
 * this parsing.
 * 
 * @param uriConverter
 *            the {@link URIConverter uri converter} to use.
 * @param documentURI
 *            URI for the document
 * @param queryEnvironment
 *            the {@link IQueryEnvironment}
 * @return the {@link DocumentTemplate} resulting from parsing the specified
 *         document
 * @throws DocumentParserException
 *             if a problem occurs while parsing the document.
 */
@SuppressWarnings("resource")
public static DocumentTemplate parseUserContent(URIConverter uriConverter, URI documentURI,
        IQueryEnvironment queryEnvironment) throws DocumentParserException {
    final DocumentTemplate result = (DocumentTemplate) EcoreUtil.create(TemplatePackage.Literals.DOCUMENT_TEMPLATE);
    final ResourceImpl r = new ResourceImpl(documentURI);

    try {
        // resources are closed in DocumentTemplate.close()
        final InputStream is = uriConverter.createInputStream(documentURI);
        final OPCPackage oPackage = OPCPackage.open(is);
        final XWPFDocument document = new XWPFDocument(oPackage);
        r.getContents().add(result);
        final BodyGeneratedParser parser = new BodyGeneratedParser(document, queryEnvironment);
        result.setBody(parser.parseBlock(null));
        result.setInputStream(is);
        result.setOpcPackage(oPackage);
        result.setDocument(document);
        for (XWPFFooter footer : document.getFooterList()) {
            final BodyGeneratedParser footerParser = new BodyGeneratedParser(footer, queryEnvironment);
            result.getFooters().add(footerParser.parseBlock(null));
        }
        for (XWPFHeader header : document.getHeaderList()) {
            final BodyGeneratedParser headerParser = new BodyGeneratedParser(header, queryEnvironment);
            result.getHeaders().add(headerParser.parseBlock(null));
        }

    } catch (IOException e) {
        throw new DocumentParserException("Unable to open " + documentURI, e);
    } catch (InvalidFormatException e1) {
        throw new DocumentParserException("Invalid .docx format " + documentURI, e1);
    }

    return result;
}
 
Example #9
Source File: TemplateResolver.java    From poi-tl with Apache License 2.0 5 votes vote down vote up
List<MetaTemplate> resolveHeaders(List<XWPFHeader> headers) {
    List<MetaTemplate> metaTemplates = new ArrayList<>();
    if (null == headers) return metaTemplates;

    headers.forEach(header -> {
        metaTemplates.addAll(resolveBodyElements(header.getBodyElements()));
    });
    return metaTemplates;
}
 
Example #10
Source File: IfTemplateRenderTest.java    From poi-tl with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("serial")
@Test
public void testIfFalse() throws Exception {
    Map<String, Object> datas = new HashMap<String, Object>() {
        {
            put("title", "poi-tl");
            put("isShowTitle", true);
            put("showUser", false);
            put("showDate", false);
        }
    };

    XWPFTemplate template = XWPFTemplate.compile("src/test/resources/template/iterable_if1.docx");
    template.render(datas);

    XWPFDocument document = XWPFTestSupport.readNewDocument(template);
    XWPFParagraph paragraph = document.getParagraphArray(0);
    assertEquals(paragraph.getText(), "Hi, poi-tl");

    XWPFTable table = document.getTableArray(0);
    XWPFTableCell cell = table.getRow(1).getCell(0);
    assertEquals(cell.getText(), "Hi, poi-tl");

    XWPFHeader header = document.getHeaderArray(0);
    paragraph = header.getParagraphArray(0);
    assertEquals(paragraph.getText(), "Hi, poi-tl");
}
 
Example #11
Source File: IfTemplateRenderTest.java    From poi-tl with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("serial")
@Test
public void testIfTrue() throws Exception {
    Map<String, Object> datas = new HashMap<String, Object>() {
        {
            put("title", "poi-tl");
            put("isShowTitle", true);
            put("showUser", new HashMap<String, Object>() {
                {
                    put("user", "Sayi");
                    put("showDate", new HashMap<String, Object>() {
                        {
                            put("date", "2020-02-10");
                        }
                    });
                }
            });
        }
    };

    XWPFTemplate template = XWPFTemplate.compile("src/test/resources/template/iterable_if1.docx");
    template.render(datas);

    XWPFDocument document = XWPFTestSupport.readNewDocument(template);
    XWPFTable table = document.getTableArray(0);
    XWPFTableCell cell = table.getRow(1).getCell(0);
    XWPFHeader header = document.getHeaderArray(0);

    testParagraph(document);
    testParagraph(cell);
    testParagraph(header);
}
 
Example #12
Source File: WatermarkServiceImpl.java    From kbase-doc with Apache License 2.0 4 votes vote down vote up
private void addWaterMark(Object obj, String watermark, String color) {
	if (obj instanceof XWPFDocument) {
		XWPFDocument doc = (XWPFDocument) obj;
		// create header-footer
		XWPFHeaderFooterPolicy headerFooterPolicy = doc.getHeaderFooterPolicy();
		if (headerFooterPolicy == null) headerFooterPolicy = doc.createHeaderFooterPolicy();
		
		// create default Watermark - fill color black and not rotated
		headerFooterPolicy.createWatermark(watermark);
		
		// get the default header
		// Note: createWatermark also sets FIRST and EVEN headers 
		// but this code does not updating those other headers
		XWPFHeader header = headerFooterPolicy.getHeader(XWPFHeaderFooterPolicy.DEFAULT);
		XWPFParagraph paragraph = header.getParagraphArray(0);
		
		// get com.microsoft.schemas.vml.CTShape where fill color and rotation is set
		XmlObject[] xmlobjects = paragraph.getCTP().getRArray(0).getPictArray(0).selectChildren(new QName("urn:schemas-microsoft-com:vml", "shape"));
		if (xmlobjects.length > 0) {
			com.microsoft.schemas.vml.CTShape ctshape = (com.microsoft.schemas.vml.CTShape)xmlobjects[0];
			// set fill color
			ctshape.setFillcolor(color);
			// set rotation
			ctshape.setStyle(ctshape.getStyle() + ";rotation:315");
		}
	} else if (obj instanceof HWPFDocument) {
		
	}
}
 
Example #13
Source File: M2DocUtils.java    From M2Doc with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Parses a template document and returns the {@link DocumentTemplate} resulting from
 * this parsing.
 * 
 * @param uriConverter
 *            the {@link URIConverter uri converter} to use.
 * @param templateURI
 *            URI for the template, used when external links (images, includes) have to be resolved
 * @param queryEnvironment
 *            the {@link IQueryEnvironment}
 * @param classProvider
 *            the {@link IClassProvider} to use for service Loading
 * @param monitor
 *            used to track the progress will generating
 * @return the {@link DocumentTemplate} resulting from parsing the specified
 *         document
 * @throws DocumentParserException
 *             if a problem occurs while parsing the document.
 */
@SuppressWarnings("resource")
public static DocumentTemplate parse(URIConverter uriConverter, URI templateURI, IQueryEnvironment queryEnvironment,
        IClassProvider classProvider, Monitor monitor) throws DocumentParserException {
    final DocumentTemplate result = (DocumentTemplate) EcoreUtil.create(TemplatePackage.Literals.DOCUMENT_TEMPLATE);
    final ResourceImpl r = new ResourceImpl(templateURI);

    try {
        monitor.beginTask("Parsing " + templateURI, TOTAL_PARSE_MONITOR_WORK);
        monitor.subTask("Loading template");
        // resources are closed in DocumentTemplate.close()
        final InputStream is = uriConverter.createInputStream(templateURI);
        final OPCPackage oPackage = OPCPackage.open(is);
        final XWPFDocument document = new XWPFDocument(oPackage);

        nextSubTask(monitor, LOAD_TEMPLATE_MONITOR_WORK, "Parsing template custom properties");

        final List<TemplateValidationMessage> messages = parseTemplateCustomProperties(queryEnvironment,
                classProvider, document);
        r.getContents().add(result);

        nextSubTask(monitor, PARSE_TEMPLATE_CUSTOM_PROPERTIES_MONITOR_WORK, "Parsing template body");
        final int unitOfWork = PARSE_TEMPLATE_MONITOR_WORK
            / (1 + document.getFooterList().size() + document.getHeaderList().size());

        final M2DocParser parser = new M2DocParser(document, queryEnvironment);
        final Block documentBody = parser.parseBlock(result.getTemplates(), TokenType.EOF);
        for (TemplateValidationMessage validationMessage : messages) {
            documentBody.getValidationMessages().add(validationMessage);
        }
        result.setBody(documentBody);
        result.setInputStream(is);
        result.setOpcPackage(oPackage);
        result.setDocument(document);

        nextSubTask(monitor, unitOfWork, "Parsing template footers");

        for (XWPFFooter footer : document.getFooterList()) {
            final M2DocParser footerParser = new M2DocParser(footer, queryEnvironment);
            result.getFooters().add(footerParser.parseBlock(null, TokenType.EOF));

            monitor.worked(unitOfWork);
        }

        nextSubTask(monitor, 0, "Parsing template headers");

        for (XWPFHeader header : document.getHeaderList()) {
            final M2DocParser headerParser = new M2DocParser(header, queryEnvironment);
            result.getHeaders().add(headerParser.parseBlock(null, TokenType.EOF));

            monitor.worked(unitOfWork);
        }

    } catch (IOException e) {
        throw new DocumentParserException("Unable to open " + templateURI, e);
    } catch (InvalidFormatException e1) {
        throw new DocumentParserException("Invalid .docx format " + templateURI, e1);
    } finally {
        monitor.done();
    }

    return result;
}