Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Perl and Win32::OLE, how can I convert a numbered list in a Word document to plain text?

I have written a Perl script to read Microsoft Word document content using Win32::OLE.

My problem is that the document containing a numbered list (starts with 1, 2, 3, …). My Perl script is not able to get that number. I can get only the text content, not the number.

Please suggest how to convert that numbered list to plain text in a way that preserves the numbering along with the text.

like image 331
Swaiya Avatar asked Feb 12 '23 22:02

Swaiya


1 Answers

My blog post Extract bullet lists from PowerPoint slides using Perl and Win32::OLE shows how to do this with PowerPoint. It turns out the task is a little simpler with Word.

#!/usr/bin/env perl

use strict;
use warnings;
use feature 'say';

use Carp qw( croak );
use Const::Fast;
use Path::Class;
use Try::Tiny;
use Win32::OLE;
use Win32::OLE::Const ('Microsoft.Word');
use Win32::OLE::Enum;

$Win32::OLE::Warn = 3;

run(@ARGV);

sub run {
    my $docfile = shift;
    # Croaks if it cannot resolve
    $docfile = file($docfile)->absolute->resolve;

    my $word = get_word();
    my $doc = $word->Documents->Open(
        {
            FileName => "$docfile",
            ConfirmConversions => 0,
            AddToRecentFiles => 0,
            Revert => 0,
            ReadOnly => 1,
        }
    );
    my $pars =  Win32::OLE::Enum->new($doc->Paragraphs);

    while (my $par = $pars->Next) {
        print_paragraph($par);
    }
}

sub print_paragraph {
    my $par = shift;
    my $range = $par->Range;
    my $fmt = $range->ListFormat;
    my $bullet = $fmt->ListString;
    my $text = $range->Text;

    unless ($bullet) {
        say $text;
        return;
    }

    my $level = $fmt->ListLevelNumber;
    say ">" x $level, join(' ', $bullet, $text);

    return;
}

sub get_word {
    my $word;

    try { $word = Win32::OLE->GetActiveObject('Word.Application') }
    catch { croak $_ };

    return $word if $word;

    $word = Win32::OLE->new('Word.Application', sub { $_[0]->Quit });
    return $word if $word;

    croak sprintf('Cannot start Word: %s', Win32::OLE->LastError);
}

Given the following Word document:

A simple Word document with bullet lists

It generates the output:

This is a document

>1. This is a numbered list
>2. Second item in the numbered list
>3. Third one

Back to normal paragraph.

>>a. Another list
>>b. Yup, here comes the second item
>>c. Not so sure what to put here
>>>i. Sub-item

Object Browser is indispensable.

like image 189
Sinan Ünür Avatar answered Apr 28 '23 03:04

Sinan Ünür