วิธีแปลง docx เป็น xhtml
ฉันพยายามหาวิธีแปลงไฟล์ docx เป็น XHTML
ฉันพบ xdocreport ซึ่งดูดี แต่ฉันมีปัญหาบางอย่าง (และฉันยังใหม่กับ xdocreport)
ตามเอกสารของพวกเขาใน github ที่นี่และที่นี่ : ฉันควรจะสามารถแปลงด้วยรหัสนี้:
String source = args[0];
String dest = args[1];
// 1) Create options DOCX to XHTML to select well converter form the registry
Options options = Options.getFrom(DocumentKind.DOCX).to(ConverterTypeTo.XHTML);
// 2) Get the converter from the registry
IConverter converter = ConverterRegistry.getRegistry().getConverter(options);
// 3) Convert DOCX to (x)html
try {
InputStream in = new FileInputStream(new File(source));
OutputStream out = new FileOutputStream(new File(dest));
converter.convert(in, out, options);
} catch (XDocConverterException | FileNotFoundException e) {
e.printStackTrace();
}
ฉันกำลังใช้การอ้างอิงเหล่านี้ (ลองใช้เวอร์ชันต่างๆเช่น 2.0.2, 2.0.0, 1.0.6):
<dependency>
<groupId>fr.opensagres.xdocreport</groupId>
<artifactId>fr.opensagres.xdocreport.document.docx</artifactId>
<version>2.0.2</version>
</dependency>
<dependency>
<groupId>fr.opensagres.xdocreport</groupId>
<artifactId>fr.opensagres.xdocreport.template.freemarker</artifactId>
<version>2.0.2</version>
</dependency>
<dependency>
<groupId>fr.opensagres.xdocreport</groupId>
<artifactId>fr.opensagres.xdocreport.converter.docx.xwpf</artifactId>
<version>2.0.2</version>
</dependency>
ปัญหาของฉัน:
- ภาพหายไป
- สีพื้นหลังหายไป (ทุกหน้ามีสีพื้นหลังซึ่งไม่ใช่สีขาวและฉันต้องแปลงสิ่งนี้ด้วย)
ฉันจะจัดการกับปัญหาเหล่านี้ได้อย่างไร? (หรือฉันจะแปลง docx เป็น xhtml โดยใช้ Docx4j ด้วยรูปแบบ / ลำดับเลข / รูปภาพได้อย่างไร)
คำตอบ
การแปลง*.docxไปXHTMLใช้XDocReportและapache poi's เป็นแหล่งที่คุณจะต้องXWPFDocument XHTMLOptionsตัวเลือกเหล่านี้จะสามารถมีการกำหนดเส้นทางสำหรับภาพที่สกัดจากImageManager XWPFDocumentจากนั้นจึงXHTMLConverterจำเป็นต้องแปลง
ตัวอย่างที่สมบูรณ์:
import java.io.*;
//needed jars: xdocreport-2.0.2.jar,
import fr.opensagres.poi.xwpf.converter.xhtml.XHTMLConverter;
import fr.opensagres.poi.xwpf.converter.xhtml.XHTMLOptions;
import fr.opensagres.poi.xwpf.converter.core.ImageManager;
//needed jars: all apache poi dependencies
import org.apache.poi.xwpf.usermodel.*;
public class DOCXToXHTMLXDocReport {
public static void main(String[] args) throws Exception {
String docPath = "./WordDocument.docx";
String root = "./";
String htmlPath = root + "WordDocument.html";
XWPFDocument document = new XWPFDocument(new FileInputStream(docPath));
XHTMLOptions options = XHTMLOptions.create().setImageManager(new ImageManager(new File(root), "images"));
FileOutputStream out = new FileOutputStream(htmlPath);
XHTMLConverter.getInstance().convert(document, out, options);
out.close();
document.close();
}
}
สิ่งนี้จัดการรูปภาพได้อย่างเหมาะสม
แต่XDocReportไม่สามารถจัดการสีพื้นหลังของหน้าXWPFDocumentได้อย่างถูกต้องจนถึงขณะนี้ จะแยกและจัดการสีพื้นหลังย่อหน้า แต่ไม่ใช่สีพื้นหลังของหน้า