user2211381
user2211381

Reputation: 31

how to set linespacing using docx4j api?

Blockquote

Hi, I am trying to convert doc to docx using docx4j api.I need to set line spacing as required.

Blockquote

Upvotes: 0

Views: 3011

Answers (1)

JasonPlutext
JasonPlutext

Reputation: 15863

You could use the following modification:

@@ -20,23 +20,30 @@

 package org.docx4j.convert.in;


 import java.io.FileInputStream;
+import java.math.BigInteger;

 import org.apache.log4j.Logger;
 import org.apache.poi.hwpf.HWPFDocument;
 import org.apache.poi.hwpf.usermodel.CharacterRun;
+import org.apache.poi.hwpf.usermodel.LineSpacingDescriptor;
 import org.apache.poi.hwpf.usermodel.Paragraph;
 import org.apache.poi.hwpf.usermodel.Range;
 import org.apache.poi.hwpf.usermodel.Section;
 import org.apache.poi.hwpf.usermodel.Table;
 import org.apache.poi.hwpf.usermodel.TableCell;
 import org.apache.poi.hwpf.usermodel.TableRow;
+import org.docx4j.XmlUtils;
+import org.docx4j.jaxb.Context;
 import org.docx4j.openpackaging.io.SaveToZipFile;
 import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
 import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart;
+import org.docx4j.wml.PPr;
+import org.docx4j.wml.PPrBase.Spacing;
+import org.docx4j.wml.STLineSpacingRule;

@@ -152,10 +161,26 @@ public class Doc {
            wmlP = documentPart.createStyledParagraphOfText( stripSpace(styleName), null);

        } else {
            wmlP = documentPart.createParagraphOfText(null);
        }
+       
+       LineSpacingDescriptor lsd = p.getLineSpacing();
+       if (lsd==null || lsd.isEmpty()) {
+           // do nothing
+       } else {
+           PPr pPr = wmlP.getPPr();
+           if (pPr==null) {
+               pPr = Context.getWmlObjectFactory().createPPr();
+               wmlP.setPPr(pPr);
+           }
+           Spacing spacing = Context.getWmlObjectFactory().createPPrBaseSpacing();
+           spacing.setLine(lsd._dyaLine);
+           spacing.setLineRule(STLineSpacingRule.AUTO);
+           pPr.setSpacing(spacing);
+       }
+       

but _dyaLine is not visible.

docx4j relies on Apache POI's HWPF to read a binary .doc, and it is in POI that a getter for _dyaLine is required.

Be aware that doc importing to docx is more a very basic proof of concept than anything else.

If you want to convert doc to docx, preserving a range of features, I'd suggest you use LibreOffice/OpenOffice via JODConverter.

Upvotes: 1

Related Questions