Search in sources :

Example 46 with P

use of org.docx4j.wml.P 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 47 with P

use of org.docx4j.wml.P in project TranskribusCore by Transkribus.

the class DocxBuilder method main.

public static void main(String[] args) throws Exception {
    WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage();
    MainDocumentPart mdp = wordMLPackage.getMainDocumentPart();
    // Setup FootnotesPart if necessary,
    // along with DocumentSettings
    FootnotesPart footnotesPart = mdp.getFootnotesPart();
    if (footnotesPart == null) {
        // that'll be the case in this example
        // initialise it
        footnotesPart = new FootnotesPart();
        mdp.addTargetPart(footnotesPart);
        CTFootnotes footnotes = (CTFootnotes) XmlUtils.unwrap(XmlUtils.unmarshalString(footnotePartXML));
        footnotesPart.setJaxbElement(footnotes);
        // Usually the settings part contains footnote properties;
        // so add these if not present
        DocumentSettingsPart dsp = mdp.getDocumentSettingsPart();
        if (dsp == null) {
            // create it
            dsp = new DocumentSettingsPart();
            mdp.addTargetPart(dsp);
        }
        CTSettings settings = dsp.getContents();
        if (settings == null) {
            settings = wmlObjectFactory.createCTSettings();
            dsp.setJaxbElement(settings);
        }
        CTFtnDocProps ftndocprops = settings.getFootnotePr();
        if (ftndocprops == null) {
            String openXML = "<w:footnotePr xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\">" + // these 2 numbers are special, and correspond with string footnotePartXML below
            "<w:footnote w:id=\"-1\"/>" + "<w:footnote w:id=\"0\"/>" + "</w:footnotePr>";
            settings.setFootnotePr((CTFtnDocProps) XmlUtils.unmarshalString(openXML, Context.jc, CTFtnDocProps.class));
        }
    }
    // Example
    // Create and add p
    org.docx4j.wml.ObjectFactory factory = Context.getWmlObjectFactory();
    org.docx4j.wml.P p = factory.createP();
    mdp.getContent().add(p);
    // Add a run
    R r = new R();
    p.getContent().add(r);
    org.docx4j.wml.Text t = factory.createText();
    t.setValue("Hello world");
    r.getContent().add(t);
    // OK, add a footnote
    addFootnote(1, "my footnote", footnotesPart, r);
    // Note: your footnote ids must be distinct; they don't need to be ordered (though Word will do that when you open the docx)
    // Save it
    wordMLPackage.save(new java.io.File("C:/Users/Administrator/footnoteTest2.docx"));
    System.out.println("Saved " + "C:/Users/Administrator/footnoteTest2.docx");
/*
		 * add comments example: Kommentar auf der rechten Seite des Dokuments
		 */
// WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage();
// 
// // Create and add a Comments Part
// CommentsPart cp = new CommentsPart();
// wordMLPackage.getMainDocumentPart().addTargetPart(cp);
// 
// // Part must have minimal contents
// Comments comments = factory.createComments();
// cp.setJaxbElement(comments);
// 
// // Add a comment to the comments part
// java.math.BigInteger commentId = BigInteger.valueOf(0);
// Comment theComment = createComment(commentId, "fred", null,
// "my first comment");
// comments.getComment().add(theComment);
// 
// // Add comment reference to document
// //P paraToCommentOn = wordMLPackage.getMainDocumentPart().addParagraphOfText("here is some content");
// P p = new P();
// 
// wordMLPackage.getMainDocumentPart().getContent().add(p);
// 
// // Create object for commentRangeStart
// CommentRangeStart commentrangestart = factory.createCommentRangeStart();
// commentrangestart.setId( commentId );  // substitute your comment id
// 
// 
// // The actual content, in the middle
// p.getContent().add(commentrangestart);
// 
// org.docx4j.wml.Text  t = factory.createText();
// t.setValue("hello");
// 
// org.docx4j.wml.R  run = factory.createR();
// run.getContent().add(t);
// 
// p.getContent().add(run);
// 
// // Create object for commentRangeEnd
// CommentRangeEnd commentrangeend = factory.createCommentRangeEnd();
// commentrangeend.setId( commentId );  // substitute your comment id
// 
// p.getContent().add(commentrangeend);
// 
// p.getContent().add(createRunCommentReference(commentId));
// 
// System.out.println(wordMLPackage.getMainDocumentPart().getXML());
// 
// 
// // ++, for next comment ...
// commentId = commentId.add(java.math.BigInteger.ONE);
// 
// wordMLPackage.save(new java.io.File("C:/Users/Administrator/commentTest.docx") );
// System.out.println("Saved " + "C:/Users/Administrator/commentTest.docx");
// 
// 
// System.out.println("Done.");
}
Also used : MainDocumentPart(org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart) WordprocessingMLPackage(org.docx4j.openpackaging.packages.WordprocessingMLPackage) File(java.io.File) R(org.docx4j.wml.R) DocumentSettingsPart(org.docx4j.openpackaging.parts.WordprocessingML.DocumentSettingsPart) CTFootnotes(org.docx4j.wml.CTFootnotes) FootnotesPart(org.docx4j.openpackaging.parts.WordprocessingML.FootnotesPart) CTFtnDocProps(org.docx4j.wml.CTFtnDocProps) CTSettings(org.docx4j.wml.CTSettings) Text(org.docx4j.wml.Text) P(org.docx4j.wml.P)

Example 48 with P

use of org.docx4j.wml.P in project mdw-designer by CenturyLinkCloud.

the class DocxBuilder method addBoldParagraph.

public P addBoldParagraph(String text) {
    ObjectFactory factory = Context.getWmlObjectFactory();
    RPr rprDoc = factory.createRPr();
    BooleanDefaultTrue b = new BooleanDefaultTrue();
    b.setVal(true);
    rprDoc.setB(b);
    P pDoc = getMdp().addParagraphOfText(text);
    R rDoc = (R) pDoc.getContent().get(0);
    rDoc.setRPr(rprDoc);
    return pDoc;
}
Also used : P(org.docx4j.wml.P) R(org.docx4j.wml.R) ObjectFactory(org.docx4j.wml.ObjectFactory) RPr(org.docx4j.wml.RPr) BooleanDefaultTrue(org.docx4j.wml.BooleanDefaultTrue)

Example 49 with P

use of org.docx4j.wml.P in project mdw-designer by CenturyLinkCloud.

the class DocxBuilder method createParagraph.

public P createParagraph(String text, int fontSize, boolean bold) {
    ObjectFactory factory = Context.getWmlObjectFactory();
    RPr rprDoc = factory.createRPr();
    if (fontSize != 0) {
        HpsMeasure size = new HpsMeasure();
        size.setVal(BigInteger.valueOf(fontSize * 2));
        rprDoc.setSz(size);
    }
    if (bold) {
        BooleanDefaultTrue b = new BooleanDefaultTrue();
        b.setVal(true);
        rprDoc.setB(b);
    }
    P pDoc = getMdp().createParagraphOfText(text);
    R rDoc = (R) pDoc.getContent().get(0);
    rDoc.setRPr(rprDoc);
    return pDoc;
}
Also used : P(org.docx4j.wml.P) R(org.docx4j.wml.R) ObjectFactory(org.docx4j.wml.ObjectFactory) RPr(org.docx4j.wml.RPr) HpsMeasure(org.docx4j.wml.HpsMeasure) BooleanDefaultTrue(org.docx4j.wml.BooleanDefaultTrue)

Example 50 with P

use of org.docx4j.wml.P in project mdw-designer by CenturyLinkCloud.

the class DocxBuilder method addBulletList.

public void addBulletList(Map<String, Object> items) throws Exception {
    if (bulletNum == null) {
        bulletNum = getNdp().addAbstractListNumberingDefinition((Numbering.AbstractNum) XmlUtils.unmarshalString(getFragment("bulletNumbering")));
        bulletNumId = bulletNum.getNumId();
    } else {
        bulletNumId = BigInteger.valueOf(ndp.restart(bulletNumId.longValue(), 0, 1));
    }
    boolean wasTable = false;
    for (String name : items.keySet()) {
        ObjectFactory factory = Context.getWmlObjectFactory();
        P listP = factory.createP();
        Object item = items.get(name);
        PPr listPpr = factory.createPPr();
        listP.setPPr(listPpr);
        Text t = factory.createText();
        R listRun = factory.createR();
        listRun.getContent().add(t);
        listP.getContent().add(listRun);
        if (item instanceof String) {
            t.setValue(name + " = " + item);
            if (wasTable)
                listPpr.setSpacing(createSpacing(100));
            wasTable = false;
        } else if (item instanceof DocxTable) {
            t.setValue(name + ":");
            listPpr.setSpacing(createSpacing(100, 10));
            wasTable = true;
        } else if (item instanceof DocxCodebox) {
            t.setValue(((DocxCodebox) item).label + ":");
            try {
                listRun.getContent().add(createCodeBox((DocxCodebox) item));
            } catch (Exception ex) {
                ex.printStackTrace();
                t.setValue(((DocxCodebox) item).label + ": ![" + ex + "]");
            }
            wasTable = false;
        }
        listPpr.setNumPr(createBulletListNumPr());
        PStyle pStyle = factory.createPPrBasePStyle();
        pStyle.setVal("ListParagraph");
        listPpr.setPStyle(pStyle);
        getMdp().addObject(listP);
        if (item instanceof DocxTable) {
            try {
                addTable((DocxTable) item);
            } catch (Exception ex) {
                ex.printStackTrace();
                t.setValue(name + ": ![" + ex + "]");
            }
        }
    }
}
Also used : Text(org.docx4j.wml.Text) PStyle(org.docx4j.wml.PPrBase.PStyle) JAXBException(javax.xml.bind.JAXBException) InvalidFormatException(org.docx4j.openpackaging.exceptions.InvalidFormatException) IOException(java.io.IOException) Docx4JException(org.docx4j.openpackaging.exceptions.Docx4JException) P(org.docx4j.wml.P) R(org.docx4j.wml.R) PPr(org.docx4j.wml.PPr) ObjectFactory(org.docx4j.wml.ObjectFactory)

Aggregations

P (org.docx4j.wml.P)101 R (org.docx4j.wml.R)58 Text (org.docx4j.wml.Text)32 Test (org.junit.Test)23 PPr (org.docx4j.wml.PPr)22 RPr (org.docx4j.wml.RPr)21 ObjectFactory (org.docx4j.wml.ObjectFactory)18 Jc (org.docx4j.wml.Jc)16 BigInteger (java.math.BigInteger)14 CTVerticalJc (org.docx4j.wml.CTVerticalJc)14 Drawing (org.docx4j.wml.Drawing)14 MainDocumentPart (org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart)13 STVerticalJc (org.docx4j.wml.STVerticalJc)11 Tc (org.docx4j.wml.Tc)11 File (java.io.File)10 Inline (org.docx4j.dml.wordprocessingDrawing.Inline)10 BinaryPartAbstractImage (org.docx4j.openpackaging.parts.WordprocessingML.BinaryPartAbstractImage)10 Tbl (org.docx4j.wml.Tbl)10 Tr (org.docx4j.wml.Tr)10 Br (org.docx4j.wml.Br)9