Search in sources :

Example 11 with MainDocumentPart

use of org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart in project docx4j-template by vindell.

the class WordprocessingMLPackageExtractor method extract.

public void extract(WordprocessingMLPackage wmlPackage, Writer out) throws Exception {
    MainDocumentPart documentPart = wmlPackage.getMainDocumentPart();
    org.docx4j.wml.Document wmlDocumentEl = documentPart.getContents();
    TextUtils.extractText(wmlDocumentEl, out);
// out.flush();
// out.close();
}
Also used : MainDocumentPart(org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart)

Example 12 with MainDocumentPart

use of org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart in project docx4j-template by vindell.

the class XHTMLImporterUtils method handle.

public static WordprocessingMLPackage handle(WordprocessingMLPackage wmlPackage, Document doc, boolean fragment, boolean altChunk) throws IOException, Docx4JException {
    // 设置转换模式
    // 转为 xhtml 格式
    doc.outputSettings().syntax(Document.OutputSettings.Syntax.xml).escapeMode(Entities.EscapeMode.xhtml);
    if (altChunk) {
        // Document对象
        MainDocumentPart document = wmlPackage.getMainDocumentPart();
        // 获取Jsoup参数
        String charsetName = Docx4jProperties.getProperty(Docx4jConstants.DOCX4J_JSOUP_PARSE_CHARSETNAME, Docx4jConstants.DEFAULT_CHARSETNAME);
        // 设置转换模式
        // 转为 xhtml 格式
        doc.outputSettings().syntax(Document.OutputSettings.Syntax.xml).escapeMode(Entities.EscapeMode.xhtml);
        // 创建html导入对象
        // XHTMLImporterImpl xhtmlImporter = new XHTMLImporterImpl(wordMLPackage);
        document.addAltChunk(AltChunkType.Xhtml, (fragment ? doc.body().html() : doc.html()).getBytes(Charset.forName(charsetName)));
        // document.addAltChunk(type, bytes, attachmentPoint)
        // document.addAltChunk(type, is)
        // document.addAltChunk(type, is, attachmentPoint)
        WordprocessingMLPackage tempPackage = document.convertAltChunks();
        // 返回处理后的WordprocessingMLPackage对象
        return tempPackage;
    }
    // 创建html导入对象
    XHTMLImporterImpl xhtmlImporter = new XHTMLImporterImpl(wmlPackage);
    // 将xhtml转换为wmlPackage可用的对象
    List<Object> list = xhtmlImporter.convert((fragment ? doc.body().html() : doc.html()), doc.baseUri());
    // 导入转换后的内容对象
    wmlPackage.getMainDocumentPart().getContent().addAll(list);
    // 返回原WordprocessingMLPackage对象
    return wmlPackage;
}
Also used : XHTMLImporterImpl(org.docx4j.convert.in.xhtml.XHTMLImporterImpl) MainDocumentPart(org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart) WordprocessingMLPackage(org.docx4j.openpackaging.packages.WordprocessingMLPackage)

Example 13 with MainDocumentPart

use of org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart in project docx4j-template by vindell.

the class WordprocessingMLTemplateWriter method writeToWriter.

public void writeToWriter(WordprocessingMLPackage wmlPackage, Writer output) throws IOException, Docx4JException {
    Assert.notNull(wmlPackage, " wmlPackage is not specified!");
    Assert.notNull(output, " output is not specified!");
    InputStream input = null;
    try {
        // Document对象
        MainDocumentPart document = wmlPackage.getMainDocumentPart();
        // Document XML
        String documentXML = XmlUtils.marshaltoString(wmlPackage.getPackage());
        // 转成字节输入流
        input = IOUtils.toBufferedInputStream(new ByteArrayInputStream(documentXML.getBytes()));
        // 获取模板输出编码格式
        String charsetName = Docx4jProperties.getProperty(Docx4jConstants.DOCX4J_CONVERT_OUT_WMLTEMPLATE_CHARSETNAME, Docx4jConstants.DEFAULT_CHARSETNAME);
        // 输出模板
        IOUtils.copy(input, output, Charset.forName(charsetName));
    } finally {
        IOUtils.closeQuietly(input);
    }
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) MainDocumentPart(org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart)

Example 14 with MainDocumentPart

use of org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart in project tutorials by eugenp.

the class Docx4jExample method isTextExist.

boolean isTextExist(String testText) throws Docx4JException, JAXBException {
    File doc = new File("helloWorld.docx");
    WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(doc);
    MainDocumentPart mainDocumentPart = wordMLPackage.getMainDocumentPart();
    String textNodesXPath = "//w:t";
    List<Object> paragraphs = mainDocumentPart.getJAXBNodesViaXPath(textNodesXPath, true);
    for (Object obj : paragraphs) {
        Text text = (Text) ((JAXBElement) obj).getValue();
        String textValue = text.getValue();
        if (textValue != null && textValue.contains(testText)) {
            return true;
        }
    }
    return false;
}
Also used : MainDocumentPart(org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart) Text(org.docx4j.wml.Text) WordprocessingMLPackage(org.docx4j.openpackaging.packages.WordprocessingMLPackage) File(java.io.File)

Example 15 with MainDocumentPart

use of org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart in project TranskribusCore by Transkribus.

the class DocxBuilder method writeDocxForDoc.

public static void writeDocxForDoc(TrpDoc doc, boolean wordBased, boolean writeTags, boolean doBlackeningSensibleData, File file, Set<Integer> pageIndices, IProgressMonitor monitor, boolean createTitle, boolean markUnclear, boolean expandAbbreviations, boolean replaceAbbrevs, boolean keepLineBreaks, boolean showSuppliedInBrackets, boolean ignoreSuppliedTags, ExportCache cache) throws JAXBException, IOException, Docx4JException, InterruptedException {
    // ch.qos.logback.classic.Logger root = logger.getClass().get(ch.qos.logback.classic.Logger) org.slf4j.LoggerFactory.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME);
    ((ch.qos.logback.classic.Logger) logger).setLevel(ch.qos.logback.classic.Level.DEBUG);
    exportTags = writeTags;
    doBlackening = doBlackeningSensibleData;
    tagnames = cache.getOnlySelectedTagnames(ExportUtils.getOnlyWantedTagnames(CustomTagFactory.getRegisteredTagNames()));
    markUnclearWords = markUnclear;
    expandAbbrevs = expandAbbreviations;
    preserveLineBreaks = keepLineBreaks;
    substituteAbbrevs = replaceAbbrevs;
    showSuppliedWithBrackets = showSuppliedInBrackets;
    ignoreSupplied = ignoreSuppliedTags;
    /*
		 * get all names of tags
		 */
    // tagnames = CustomTagFactory.getRegisteredTagNames();
    // main document part
    wordMLPackage = WordprocessingMLPackage.createPackage();
    MainDocumentPart mdp = wordMLPackage.getMainDocumentPart();
    org.docx4j.wml.ObjectFactory factory = Context.getWmlObjectFactory();
    List<TrpPage> pages = doc.getPages();
    int totalPages = pageIndices == null ? pages.size() : pageIndices.size();
    if (monitor != null) {
        monitor.beginTask("Exporting to docx", totalPages);
    }
    int c = 0;
    boolean atLeastOnePageWritten = false;
    // can be used as page break every time we need one
    Br objBr = new Br();
    objBr.setType(STBrType.PAGE);
    P pageBreakP = factory.createP();
    pageBreakP.getContent().add(objBr);
    for (int i = 0; i < pages.size(); ++i) {
        if (pageIndices != null && !pageIndices.contains(i))
            continue;
        if (!atLeastOnePageWritten && createTitle) {
            addTitlePage(doc, mdp);
            // add page break
            mdp.addObject(pageBreakP);
        }
        if (monitor != null) {
            if (monitor.isCanceled()) {
                throw new InterruptedException("Export canceled by the user");
            // logger.debug("docx export cancelled!");
            // return;
            }
            monitor.subTask("Processing page " + (c + 1));
        }
        // TrpPage page = pages.get(i);
        // TrpTranscriptMetadata md = page.getCurrentTranscript();
        // JAXBPageTranscript tr = new JAXBPageTranscript(md);
        // tr.build();
        JAXBPageTranscript tr = null;
        if (cache != null) {
            tr = cache.getPageTranscriptAtIndex(i);
        }
        if (tr == null) {
            TrpPage page = pages.get(i);
            TrpTranscriptMetadata md = page.getCurrentTranscript();
            // md.getStatus().equals("Done");
            tr = new JAXBPageTranscript(md);
            tr.build();
        }
        TrpPageType trpPage = tr.getPage();
        logger.debug("writing docx for the page " + (i + 1) + "/" + doc.getNPages());
        writeDocxForTranscriptWithTables(mdp, trpPage, wordBased, preserveLineBreaks);
        atLeastOnePageWritten = true;
        ++c;
        if (monitor != null) {
            monitor.worked(c);
        }
    }
    P p = factory.createP();
    mdp.getContent().add(p);
    addComplexField(p, " INDEX \\e \"", "\" \\c \"1\" \\z \"1031\"");
    FieldUpdater updater = new FieldUpdater(wordMLPackage);
    updater.update(true);
    // write tags at end of last page
    if (false) {
        // RtfText headline = RtfText.text("Person names in this document (amount of found persons: " + persons.size() + ")", "\n");
        logger.debug("export tags ");
        boolean firstExport = true;
        // tagnames = all user choosen tags via export dialog
        for (String currTagname : tagnames) {
            // logger.debug("curr tagname " + currTagname);
            // get all custom tags with currTagname and text
            HashMap<CustomTag, String> allTagsOfThisTagname = cache.getTags(currTagname);
            // one paragraph for each tagname
            org.docx4j.wml.P p4Tag = factory.createP();
            if (allTagsOfThisTagname.size() > 0 && !currTagname.equals("textStyle") && !currTagname.equals("gap") && !currTagname.equals("comment")) {
                // new page if tag export starts
                if (firstExport) {
                    // Br objBr = new Br();
                    // objBr.setType(STBrType.PAGE);
                    p4Tag.getContent().add(objBr);
                    firstExport = false;
                }
                // logger.debug("allTagsOfThisTagname " + allTagsOfThisTagname.size());
                // one run for headline and thanfor each entry
                org.docx4j.wml.Text t = factory.createText();
                t.setValue(currTagname + " tags in this document: " + allTagsOfThisTagname.size());
                t.setSpace("preserve");
                org.docx4j.wml.R run = factory.createR();
                run.getContent().add(t);
                org.docx4j.wml.RPr rpr = factory.createRPr();
                org.docx4j.wml.BooleanDefaultTrue b = new org.docx4j.wml.BooleanDefaultTrue();
                b.setVal(true);
                U u = factory.createU();
                u.setVal(UnderlineEnumeration.SINGLE);
                rpr.setB(b);
                rpr.setU(u);
                run.setRPr(rpr);
                // this Br element is used break the current and go for next line
                Br br = factory.createBr();
                run.getContent().add(br);
                p4Tag.getContent().add(run);
                // ArrayList<RtfText> tagTexts = new ArrayList<RtfText>();
                Collection<String> valueSet = allTagsOfThisTagname.values();
                int l = 0;
                for (String currEntry : valueSet) {
                    org.docx4j.wml.R currRun = factory.createR();
                    org.docx4j.wml.Text currText = factory.createText();
                    currText.setValue(currEntry);
                    currText.setSpace("preserve");
                    currRun.getContent().add(currText);
                    // reuse linebreak
                    currRun.getContent().add(br);
                    p4Tag.getContent().add(currRun);
                }
            }
            mdp.getContent().add(p4Tag);
        }
    }
    // finally save the file
    wordMLPackage.save(file);
    logger.info("Saved " + file.getAbsolutePath());
}
Also used : JAXBPageTranscript(eu.transkribus.core.model.beans.JAXBPageTranscript) TrpTranscriptMetadata(eu.transkribus.core.model.beans.TrpTranscriptMetadata) CustomTag(eu.transkribus.core.model.beans.customtags.CustomTag) Logger(org.slf4j.Logger) RPr(org.docx4j.wml.RPr) P(org.docx4j.wml.P) U(org.docx4j.wml.U) R(org.docx4j.wml.R) Text(org.docx4j.wml.Text) TrpPageType(eu.transkribus.core.model.beans.pagecontent_trp.TrpPageType) P(org.docx4j.wml.P) FieldUpdater(org.docx4j.model.fields.FieldUpdater) TrpPage(eu.transkribus.core.model.beans.TrpPage) MainDocumentPart(org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart) Br(org.docx4j.wml.Br)

Aggregations

MainDocumentPart (org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart)36 WordprocessingMLPackage (org.docx4j.openpackaging.packages.WordprocessingMLPackage)22 File (java.io.File)19 P (org.docx4j.wml.P)13 ObjectFactory (org.docx4j.wml.ObjectFactory)7 Text (org.docx4j.wml.Text)7 Body (org.docx4j.wml.Body)5 Br (org.docx4j.wml.Br)5 R (org.docx4j.wml.R)5 RPr (org.docx4j.wml.RPr)5 Tbl (org.docx4j.wml.Tbl)5 TraversalUtil (org.docx4j.TraversalUtil)4 Relationship (org.docx4j.relationships.Relationship)4 Tr (org.docx4j.wml.Tr)4 Tc (org.docx4j.wml.Tc)3 Child (org.jvnet.jaxb2_commons.ppp.Child)3 ByteArrayInputStream (java.io.ByteArrayInputStream)2 InputStream (java.io.InputStream)2 BigInteger (java.math.BigInteger)2 ArrayList (java.util.ArrayList)2