Skip to content

Table Alignment Issue in DOCX to PDF Conversion #699

@dcaruso-RatedPower

Description

@dcaruso-RatedPower

Hello, can you please help me on this issue? Thanks a lot.

Problem

When converting a XWPF document with centered tables to PDF using the fr.opensagres.xdocreport:fr.opensagres.poi.xwpf.converter.pdf.PdfConverter, the tables appear left-aligned in the output PDF.

You can find attached a screenshot that highlights the issue. (DOCX on the left and PDF on the right).

Image

Possible Root Cause

There's a value mismatch between the alignment enums used:

  • In TableRowAlign: CENTER(STJcTable.INT_CENTER) = 1
  • In ParagraphAlignment: CENTER(STJc.INT_CENTER) = 2

The TableAlignmentValueProvider incorrectly uses ParagraphAlignment.valueOf(tblPr.getJc().getVal().intValue()),
causing it to interpret value 1 (CENTER in table context) as START in paragraph context.

Expected Behavior

Table alignment should be correctly preserved when converting from DOCX to PDF.

Test to reproduce the issue

This is a test that reproduce the issue, I attached this template.docx that you can use to run the test. This template should be added to a test folder.

import fr.opensagres.poi.xwpf.converter.pdf.PdfConverter;
import fr.opensagres.poi.xwpf.converter.pdf.PdfOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.junit.jupiter.api.Test;

import java.io.FileOutputStream;
import java.io.File;

class TableAlignmentTest {

    @Test
    void testDemonstrateTableAlignmentIssue() throws Exception {
        // Get test directory path
        String testDir = System.getProperty("user.dir") + "/test/";

        // Create directory if it doesn't exist
        new File(testDir).mkdirs();

        String docxPath = testDir + "centered_table-" + System.currentTimeMillis() + ".docx";
        String pdfPath = testDir + "centered_table-" + System.currentTimeMillis() + ".pdf";

        // Create a document with a centered table
        String templateFile = testDir + "template.docx";
        XWPFDocument document = new XWPFDocument(new java.io.FileInputStream(templateFile));

        // Save DOCX
        try (FileOutputStream out = new FileOutputStream(docxPath)) {
            document.write(out);
        }

        // Convert to PDF
        PdfOptions options = PdfOptions.create();
        try (FileOutputStream out = new FileOutputStream(pdfPath)) {
            PdfConverter.getInstance().convert(document, out, options);
        }

        // Log files location
        System.out.println("Files saved to: " + testDir);

        // The table present in the PDF is not centered
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions