Search in sources :

Example 1 with FieldUpdater

use of org.docx4j.model.fields.FieldUpdater 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)

Example 2 with FieldUpdater

use of org.docx4j.model.fields.FieldUpdater in project docx4j-template by vindell.

the class WordprocessingMLPackageWriter method writeToPDFWhithFo.

/**
 * 将 {@link org.docx4j.openpackaging.packages.WordprocessingMLPackage} 存为 pdf
 */
public void writeToPDFWhithFo(WordprocessingMLPackage wmlPackage, OutputStream output) throws IOException, Docx4JException {
    Assert.notNull(wmlPackage, " wmlPackage is not specified!");
    Assert.notNull(output, " output is not specified!");
    try {
        // Font regex (optional)
        // Set regex if you want to restrict to some defined subset of fonts
        // Here we have to do this before calling createContent,
        // since that discovers fonts
        // String regex = null;
        // Refresh the values of DOCPROPERTY fields
        FieldUpdater updater = new FieldUpdater(wmlPackage);
        updater.update(true);
        // .. example of mapping font Times New Roman which doesn't have certain Arabic glyphs
        // eg Glyph "ي" (0x64a, afii57450) not available in font "TimesNewRomanPS-ItalicMT".
        // eg Glyph "ج" (0x62c, afii57420) not available in font "TimesNewRomanPS-ItalicMT".
        // to a font which does
        PhysicalFonts.get("Arial Unicode MS");
        // FO exporter setup (required)
        // .. the FOSettings object
        FOSettings foSettings = Docx4J.createFOSettings();
        foSettings.setWmlPackage(wmlPackage);
        foSettings.setApacheFopMime("application/pdf");
        // Document format:
        // The default implementation of the FORenderer that uses Apache Fop will output
        // a PDF document if nothing is passed via
        // foSettings.setApacheFopMime(apacheFopMime)
        // apacheFopMime can be any of the output formats defined in org.apache.fop.apps.MimeConstants eg org.apache.fop.apps.MimeConstants.MIME_FOP_IF or
        // FOSettings.INTERNAL_FO_MIME if you want the fo document as the result.
        // foSettings.setApacheFopMime(FOSettings.INTERNAL_FO_MIME);
        // Specify whether PDF export uses XSLT or not to create the FO
        // (XSLT takes longer, but is more complete).
        // Don't care what type of exporter you use
        Docx4J.toFO(foSettings, output, Docx4J.FLAG_EXPORT_PREFER_XSL);
        // Prefer the exporter, that uses a xsl transformation
        // Docx4J.toFO(foSettings, os, Docx4J.FLAG_EXPORT_PREFER_XSL);
        // Prefer the exporter, that doesn't use a xsl transformation (= uses a visitor)
        // faster, but not yet at feature parity
        // Docx4J.toFO(foSettings, os, Docx4J.FLAG_EXPORT_PREFER_NONXSL);
        // Clean up, so any ObfuscatedFontPart temp files can be deleted
        // if (wordMLPackage.getMainDocumentPart().getFontTablePart()!=null) {
        // wordMLPackage.getMainDocumentPart().getFontTablePart().deleteEmbeddedFontTempFiles();
        // }
        // This would also do it, via finalize() methods
        updater = null;
        foSettings = null;
        wmlPackage = null;
    } finally {
        IOUtils.closeQuietly(output);
    }
}
Also used : FieldUpdater(org.docx4j.model.fields.FieldUpdater) FOSettings(org.docx4j.convert.out.FOSettings)

Aggregations

FieldUpdater (org.docx4j.model.fields.FieldUpdater)2 JAXBPageTranscript (eu.transkribus.core.model.beans.JAXBPageTranscript)1 TrpPage (eu.transkribus.core.model.beans.TrpPage)1 TrpTranscriptMetadata (eu.transkribus.core.model.beans.TrpTranscriptMetadata)1 CustomTag (eu.transkribus.core.model.beans.customtags.CustomTag)1 TrpPageType (eu.transkribus.core.model.beans.pagecontent_trp.TrpPageType)1 FOSettings (org.docx4j.convert.out.FOSettings)1 MainDocumentPart (org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart)1 Br (org.docx4j.wml.Br)1 P (org.docx4j.wml.P)1 R (org.docx4j.wml.R)1 RPr (org.docx4j.wml.RPr)1 Text (org.docx4j.wml.Text)1 U (org.docx4j.wml.U)1 Logger (org.slf4j.Logger)1