pax_global_header 0000666 0000000 0000000 00000000064 14553521277 0014525 g ustar 00root root 0000000 0000000 52 comment=f30fb2bbbd90aa9aaed1d79b9aaad8979cbde47c
pdf2docx-0.5.8/ 0000775 0000000 0000000 00000000000 14553521277 0013250 5 ustar 00root root 0000000 0000000 pdf2docx-0.5.8/.github/ 0000775 0000000 0000000 00000000000 14553521277 0014610 5 ustar 00root root 0000000 0000000 pdf2docx-0.5.8/.github/workflows/ 0000775 0000000 0000000 00000000000 14553521277 0016645 5 ustar 00root root 0000000 0000000 pdf2docx-0.5.8/.github/workflows/publish.yml 0000664 0000000 0000000 00000006662 14553521277 0021050 0 ustar 00root root 0000000 0000000 # Create release and publish to Pypi when pushing tags
name: publish
# Trigger the workflow on push tags, matching vM.n.p, i.e. v3.2.10
on:
push:
tags:
- 'v[0-9]+.[0-9]+.[0-9]+'
# Jobs to do:
# - build package
# - create release with asset
# - publish to Pypi
jobs:
# -----------------------------------------------------------
# create python env and setup package
# -----------------------------------------------------------
build:
# The type of runner that the job will run on
runs-on: ubuntu-latest
# Steps represent a sequence of tasks that will be executed as part of the job
steps:
- name: Check out code
uses: actions/checkout@v2
- name: Set up Python 3.x
uses: actions/setup-python@v1
with:
python-version: '3.10'
- name: Display Python version
run: python -c "import sys; print(sys.version)"
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install setuptools wheel pytest
# build package for tags, e.g. 3.2.1 extracted from 'refs/tags/v3.2.1'
- name: Build package
run: |
echo ${GITHUB_REF#refs/tags/v} > version.txt
python setup.py sdist --formats=gztar,zip
python setup.py bdist_wheel
# test wheel file locally
- name: Test package
run: |
pip install ./dist/*.whl
cd test
pytest -v test.py::TestConversion
# upload the artifacts for further jobs
# - app-tag.tar.gz
# - app-tag.zip
# - app-tag-info.whl
- name: Archive package
uses: actions/upload-artifact@v2
with:
name: dist
path: ./dist
# -----------------------------------------------------------
# create release and upload asset
# -----------------------------------------------------------
release:
runs-on: ubuntu-latest
# Run this job after build completes successfully
needs: build
steps:
- name: Checkout code
uses: actions/checkout@v2
# download artifacts from job: build
- name: Download artifacts from build
uses: actions/download-artifact@v2
with:
name: dist
path: dist
# create release and upload assets
- name: Create release with assets
uses: softprops/action-gh-release@v1
with:
files: |
./dist/*.tar.gz
./dist/*.zip
./dist/*.whl
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
# -----------------------------------------------------------
# publish to Pypi
# -----------------------------------------------------------
publish:
runs-on: ubuntu-latest
# Run this job after both build and release completes successfully
needs: [build, release]
steps:
- name: Checkout code
uses: actions/checkout@v2
- name: Download artifacts from release
uses: actions/download-artifact@v2
with:
name: dist
path: dist
# Error when two sdist files created in build job are uploaded to Pipi:
# HTTPError: 400 Bad Request from https://upload.pypi.org/legacy/
# Only one sdist may be uploaded per release.
- name: Remove duplicated sdist
run: rm ./dist/*.zip
- name: Publish to PyPI
uses: pypa/gh-action-pypi-publish@master
with:
password: ${{ secrets.PYPI_PASSWORD }} pdf2docx-0.5.8/.github/workflows/test.yml 0000664 0000000 0000000 00000004631 14553521277 0020353 0 ustar 00root root 0000000 0000000 # Run test when triggering the workflow on push and pull request,
# but only for the master branch
name: test
on:
push:
branches:
- master
pull_request:
branches:
- master
# -----------------------------------------------------------------------------------------------------
# To leverage the benefit of Github Action, the testing process is divided into three jobs:
# 1. pdf2docx: convert sample pdf to docx -> linux runner
# 2. docx2pdf: convert generated docx to pdf for comparing -> specific runner with MS Word installed
# 3. check_quality: convert page to image and compare similarity with python-opencv -> linux runner
# However, keep step 1 only, considering the difficulty to get a specific runner with MS Word installed.
# -----------------------------------------------------------------------------------------------------
jobs:
pdf2docx-docker:
runs-on: ubuntu-latest
container:
image: python:3.8
steps:
- name: Check out code
uses: actions/checkout@v2
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements.txt
pip install pytest
python setup.py develop
- name: Run unit test
run: |
pytest -v ./test/test.py::TestConversion
pdf2docx-ubuntu:
runs-on: ubuntu-latest
needs: pdf2docx-docker
strategy:
matrix:
python-version: ["3.8", "3.9", "3.10"]
steps:
- name: Check out code
uses: actions/checkout@v2
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v2
with:
python-version: ${{ matrix.python-version }}
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements.txt
pip install pytest pytest-cov
python setup.py develop
- name: Run unit test
run: |
pytest -v ./test/test.py::TestConversion --cov=./pdf2docx --cov-report=xml
- name: Upload coverage reports to Codecov
uses: codecov/codecov-action@v3
with: # Or as an environment variable
token: ${{ secrets.CODECOV_TOKEN }}
# upload docx for further job
- name: Archive package
uses: actions/upload-artifact@v2
with:
name: outputs
path: ./test/outputs pdf2docx-0.5.8/.gitignore 0000664 0000000 0000000 00000000314 14553521277 0015236 0 ustar 00root root 0000000 0000000 # files
*.pyc
*.jp*g
*.docx
layout.json
.vscode/
# pdf testing files
*.pdf
!demo*.pdf
*coverage*
test/issues/
test/features/
test/outputs/
diff.png
# building dir
build/
dist/
*egg-info/
pdf2docx*.rst pdf2docx-0.5.8/.readthedocs.yaml 0000664 0000000 0000000 00000001336 14553521277 0016502 0 ustar 00root root 0000000 0000000 # .readthedocs.yaml
# Read the Docs configuration file
# See https://docs.readthedocs.io/en/stable/config-file/v2.html for details
# Required
version: 2
# Set the version of Python and other tools you might need
build:
os: ubuntu-20.04
tools:
python: "3.9"
# You can also specify other tool versions:
# nodejs: "16"
# rust: "1.55"
# golang: "1.17"
# Build documentation in the docs/ directory with Sphinx
sphinx:
configuration: doc/conf.py
# If using Sphinx, optionally build your docs in additional formats such as PDF
#formats:
# - pdf
# Optionally declare the Python requirements required to build your docs
python:
install:
- requirements: doc/requirements.txt
pdf2docx-0.5.8/AFFERO GPL 0000664 0000000 0000000 00000103303 14553521277 0014540 0 ustar 00root root 0000000 0000000 GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see .
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
. pdf2docx-0.5.8/LICENSE 0000664 0000000 0000000 00000104514 14553521277 0014262 0 ustar 00root root 0000000 0000000 GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see .
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
Copyright (C)
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
. pdf2docx-0.5.8/MANIFEST.in 0000664 0000000 0000000 00000000156 14553521277 0015010 0 ustar 00root root 0000000 0000000 include *.md
include LICENSE*
include requirements.txt
prune test
include test/*.py
include test/samples/*.pdf pdf2docx-0.5.8/Makefile 0000664 0000000 0000000 00000001753 14553521277 0014716 0 ustar 00root root 0000000 0000000 # Project makefile
# working directories and files
#
TOPDIR :=$(shell pwd)
SRC :=$(TOPDIR)/pdf2docx
BUILD :=$(TOPDIR)/build
DOCSRC :=$(TOPDIR)/doc
TEST :=$(TOPDIR)/test
CLEANDIRS :=.pytest_cache pdf2docx.egg-info dist
# pip install sphinx_rtd_theme
.PHONY: src doc test clean
src:
@python setup.py sdist --formats=gztar,zip && \
python setup.py bdist_wheel
doc:
@if [ -f "$(DOCSRC)/Makefile" ] ; then \
( cd "$(DOCSRC)" && make html MODULEDIR="$(SRC)" BUILDDIR="$(BUILD)" ) || exit 1 ; \
fi
test:
@if [ -f "$(TEST)/Makefile" ] ; then \
( cd "$(TEST)" && make test SOURCEDIR="$(SRC)" ) || exit 1 ; \
fi
clean:
@if [ -e "$(DOCSRC)/Makefile" ] ; then \
( cd "$(DOCSRC)" && make $@ BUILDDIR="$(BUILD)" ) || exit 0 ; \
fi
@for p in $(CLEANDIRS) ; do \
if [ -d "$(TOPDIR)/$$p" ]; then rm -rf "$(TOPDIR)/$$p" ; fi ; \
done
@if [ -d "$(BUILD)" ]; then rm -rf "$(BUILD)" ; fi
@if [ -e "$(TEST)/Makefile" ] ; then \
( cd "$(TEST)" && make $@ ) || exit 0 ; \
fi pdf2docx-0.5.8/README.md 0000664 0000000 0000000 00000005171 14553521277 0014533 0 ustar 00root root 0000000 0000000 English | [中文](README_CN.md)
# pdf2docx

[](https://codecov.io/gh/dothinking/pdf2docx)
[](https://pypi.python.org/pypi/pdf2docx/)


- Extract data from PDF with `PyMuPDF`, e.g. text, images and drawings
- Parse layout with rule, e.g. sections, paragraphs, images and tables
- Generate docx with `python-docx`
## Features
- Parse and re-create page layout
- page margin
- section and column (1 or 2 columns only)
- page header and footer [TODO]
- Parse and re-create paragraph
- OCR text [TODO]
- text in horizontal/vertical direction: from left to right, from bottom to top
- font style, e.g. font name, size, weight, italic and color
- text format, e.g. highlight, underline, strike-through
- list style [TODO]
- external hyper link
- paragraph horizontal alignment (left/right/center/justify) and vertical spacing
- Parse and re-create image
- in-line image
- image in Gray/RGB/CMYK mode
- transparent image
- floating image, i.e. picture behind text
- Parse and re-create table
- border style, e.g. width, color
- shading style, i.e. background color
- merged cells
- vertical direction cell
- table with partly hidden borders
- nested tables
- Parsing pages with multi-processing
*It can also be used as a tool to extract table contents since both table content and format/style is parsed.*
## Limitations
- Text-based PDF file
- Left to right language
- Normal reading direction, no word transformation / rotation
- Rule-based method can't 100% convert the PDF layout
## Documentation
- [Installation](https://pdf2docx.readthedocs.io/en/latest/installation.html)
- [Quickstart](https://pdf2docx.readthedocs.io/en/latest/quickstart.html)
- [Convert PDF](https://pdf2docx.readthedocs.io/en/latest/quickstart.convert.html)
- [Extract table](https://pdf2docx.readthedocs.io/en/latest/quickstart.table.html)
- [Command Line Interface](https://pdf2docx.readthedocs.io/en/latest/quickstart.cli.html)
- [Graphic User Interface](https://pdf2docx.readthedocs.io/en/latest/quickstart.gui.html)
- [Technical Documentation (In Chinese)](https://pdf2docx.readthedocs.io/en/latest/techdoc.html)
- [API Documentation](https://pdf2docx.readthedocs.io/en/latest/modules.html)
## Sample
 pdf2docx-0.5.8/README_CN.md 0000664 0000000 0000000 00000005040 14553521277 0015106 0 ustar 00root root 0000000 0000000 [English](README.md) | 中文
# pdf2docx

[](https://codecov.io/gh/dothinking/pdf2docx)
[](https://pypi.python.org/pypi/pdf2docx/)


- 基于 `PyMuPDF` 提取文本、图片、矢量等原始数据
- 基于规则解析章节、段落、表格、图片、文本等布局及样式
- 基于 `python-docx` 创建Word文档
## 主要功能
- 解析和创建页面布局
- 页边距
- 章节和分栏 (目前最多支持两栏布局)
- 页眉和页脚 [TODO]
- 解析和创建段落
- OCR 文本 [TODO]
- 水平(从左到右)或竖直(自底向上)方向文本
- 字体样式例如字体、字号、粗/斜体、颜色
- 文本样式例如高亮、下划线和删除线
- 列表样式 [TODO]
- 外部超链接
- 段落水平对齐方式 (左/右/居中/分散对齐)及前后间距
- 解析和创建图片
- 内联图片
- 灰度/RGB/CMYK等颜色空间图片
- 带有透明通道图片
- 浮动图片(衬于文字下方)
- 解析和创建表格
- 边框样式例如宽度和颜色
- 单元格背景色
- 合并单元格
- 单元格垂直文本
- 隐藏部分边框线的表格
- 嵌套表格
- 支持多进程转换
*`pdf2docx`同时解析出了表格内容和样式,因此也可以作为一个表格内容提取工具。*
## 限制
- 目前暂不支持扫描PDF文字识别
- 仅支持从左向右书写的语言(因此不支持阿拉伯语)
- 不支持旋转的文字
- 基于规则的解析无法保证100%还原PDF样式
## 使用帮助
- [安装](https://pdf2docx.readthedocs.io/en/latest/installation.html)
- [快速上手](https://pdf2docx.readthedocs.io/en/latest/quickstart.html)
- [转换PDF](https://pdf2docx.readthedocs.io/en/latest/quickstart.convert.html)
- [提取表格](https://pdf2docx.readthedocs.io/en/latest/quickstart.table.html)
- [命令行参数](https://pdf2docx.readthedocs.io/en/latest/quickstart.cli.html)
- [简单图形界面](https://pdf2docx.readthedocs.io/en/latest/quickstart.gui.html)
- [技术手册](https://pdf2docx.readthedocs.io/en/latest/techdoc.html)
- [API手册](https://pdf2docx.readthedocs.io/en/latest/modules.html)
## 样例
 pdf2docx-0.5.8/doc/ 0000775 0000000 0000000 00000000000 14553521277 0014015 5 ustar 00root root 0000000 0000000 pdf2docx-0.5.8/doc/Makefile 0000664 0000000 0000000 00000000715 14553521277 0015460 0 ustar 00root root 0000000 0000000 # Minimal makefile for Sphinx documentation
#
# MODULEDIR and BUILDDIR are set in top makefile
SOURCEDIR = .
TARGETDIR = doctrees html
.PHONY: html clean
html: Makefile
@sphinx-apidoc --separate -o "$(SOURCEDIR)" "$(MODULEDIR)" && \
sphinx-build -M html "$(SOURCEDIR)" "$(BUILDDIR)"
clean:
@for p in $(TARGETDIR) ; do \
if [ -d "$(BUILDDIR)/$$p" ]; then rm -rf "$(BUILDDIR)/$$p" ; fi ; \
done
@if [ -e modules.rst ]; then rm pdf2docx*.rst ; fi pdf2docx-0.5.8/doc/api/ 0000775 0000000 0000000 00000000000 14553521277 0014566 5 ustar 00root root 0000000 0000000 pdf2docx-0.5.8/doc/api/modules.rst 0000664 0000000 0000000 00000000075 14553521277 0016772 0 ustar 00root root 0000000 0000000 pdf2docx
========
.. toctree::
:maxdepth: 4
pdf2docx
pdf2docx-0.5.8/doc/conf.py 0000664 0000000 0000000 00000010331 14553521277 0015312 0 ustar 00root root 0000000 0000000 # Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
import os
import sys
sys.path.insert(0, os.path.abspath("../pdf2docx/"))
# -- Project information -----------------------------------------------------
project = 'pdf2docx'
copyright = '2023, Artifex'
author = 'Artifex Software, Inc.'
# The full version, including alpha/beta/rc tags
# read version number from version.txt, otherwise alpha version
# Github CI can create version.txt dynamically.
def get_version(fname):
if os.path.exists(fname):
with open(fname, 'r') as f:
version = f.readline().strip()
else:
version = 'alpha'
return version
release = get_version('../version.txt')
# -- General configuration ---------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinxcontrib.apidoc'
]
apidoc_module_dir = '../pdf2docx'
apidoc_output_dir = 'api'
apidoc_excluded_paths = []
apidoc_separate_modules = True
# Add any paths that contain templates here, relative to this directory.
# templates_path = ['_templates']
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = [
]
# -- Options for HTML output -------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
# html_theme = 'alabaster'
html_theme = 'sphinx_rtd_theme'
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
# html_static_path = ['_static']
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# "fontpkg": r"\usepackage[sfdefault]{ClearSans} \usepackage[T1]{fontenc}"
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [("index", "pdf2docx.tex", "pdf2docx Documentation", "Artifex", "manual")]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = "images/pymupdf-logo.png"
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
# latex_use_parts = False
# If true, show page references after internal links.
latex_show_pagerefs = False
# If true, show URL addresses after external links.
# latex_show_urls = True
# latex_use_xindy = True
# Documents to append as an appendix to all manuals.
# latex_appendices = []
# If false, no module index is generated.
latex_domain_indices = True
# -- Options for PDF output --------------------------------------------------
# Grouping the document tree into PDF files. List of tuples
# (source start file, target name, title, author).
pdf_documents = [("index", "pdf2docx", "pdf2docx manual", "Artifex")]
# A comma-separated list of custom stylesheets. Example:
# pdf_stylesheets = ["sphinx", "bahnschrift", "a4"]
# Create a compressed PDF
pdf_compressed = True
# A colon-separated list of folders to search for fonts. Example:
# pdf_font_path=['/usr/share/fonts', '/usr/share/texmf-dist/fonts/']
# Language to be used for hyphenation support
pdf_language = "en_US"
# If false, no index is generated.
pdf_use_index = True
# If false, no modindex is generated.
pdf_use_modindex = True
# If false, no coverpage is generated.
pdf_use_coverpage = True
pdf_break_level = 2
pdf_verbosity = 0
pdf_invariant = True
pdf2docx-0.5.8/doc/index.rst 0000664 0000000 0000000 00000001107 14553521277 0015655 0 ustar 00root root 0000000 0000000 Welcome to pdf2docx's documentation!
====================================
`pdf2docx `_ is a Python library
to extract data from PDF with ``PyMuPDF``, parse layout with rule, and
generate docx file with ``python-docx``.
.. image:: https://s1.ax1x.com/2020/08/04/aDryx1.png
.. toctree::
:maxdepth: 2
:caption: USER GUIDE
installation
quickstart
techdoc
.. toctree::
:maxdepth: 2
:caption: API DOCUMENTATION
api/modules
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
pdf2docx-0.5.8/doc/installation.rst 0000664 0000000 0000000 00000001664 14553521277 0017257 0 ustar 00root root 0000000 0000000 Installation
====================
``pdf2docx`` can be installed from either Pypi or the source code.
Install from Pypi
-------------------
Type the command below for a new installation::
$ pip install pdf2docx
Or, upgrade this library with::
$ pip install --upgrade pdf2docx
Install from source code remotely
--------------------------------------
Install ``pdf2docx`` directly from the ``master`` branch::
$ pip install git+git://github.com/dothinking/pdf2docx.git@master --upgrade
.. note::
In this way, ``pdf2docx`` might have a higher version than Pypi, which is not released yet.
Install from source code locally
---------------------------------------
Clone or download `pdf2docx `_, navigate to the root directory and run::
$ python setup.py install
Or, install it in developing mode::
$ python setup.py develop
Uninstall
--------------
::
$ pip uninstall pdf2docx pdf2docx-0.5.8/doc/quickstart.cli.rst 0000664 0000000 0000000 00000003265 14553521277 0017515 0 ustar 00root root 0000000 0000000 Command Line Interface
===========================
::
$ pdf2docx --help
NAME
pdf2docx - Command line interface for pdf2docx.
SYNOPSIS
pdf2docx COMMAND | -
DESCRIPTION
Command line interface for pdf2docx.
COMMANDS
COMMAND is one of the following:
convert
Convert pdf file to docx file.
debug
Convert one PDF page and plot layout information for debugging.
table
Extract table content from pdf pages.
By range of pages
-----------------------
Specify pages range by ``--start`` (from the first page if omitted) and
``--end`` (to the last page if omitted).
.. note::
The page index is zero-based by default, but can turn it off by
``--zero_based_index=False``, i.e. the first page index starts from 1.
Convert all pages::
$ pdf2docx convert test.pdf test.docx
Convert pages from the second to the end::
$ pdf2docx convert test.pdf test.docx --start=1
Convert pages from the first to the third (index=2)::
$ pdf2docx convert test.pdf test.docx --end=3
Convert second and third pages::
$ pdf2docx convert test.pdf test.docx --start=1 --end=3
Convert the first and second pages with zero-based index turn off::
$ pdf2docx convert test.pdf test.docx --start=1 --end=3 --zero_based_index=False
By page numbers
-----------------------
Convert the first, third and 5th pages::
$ pdf2docx convert test.pdf test.docx --pages=0,2,4
Multi-Processing
--------------------------
Turn on multi-processing with default count of CPU::
$ pdf2docx convert test.pdf test.docx --multi_processing=True
Specify the count of CPUs::
$ pdf2docx convert test.pdf test.docx --multi_processing=True --cpu_count=4 pdf2docx-0.5.8/doc/quickstart.convert.rst 0000664 0000000 0000000 00000004071 14553521277 0020422 0 ustar 00root root 0000000 0000000 Convert PDF
=======================
We can use either the :py:class:`~pdf2docx.converter.Converter` class, or
a wrapped method :py:meth:`~pdf2docx.main.parse` to convert all/specified
pdf pages to docx. Multi-processing is supported in case pdf file with a
large number of pages.
Example 1: convert all pages
----------------------------------
::
from pdf2docx import Converter
pdf_file = '/path/to/sample.pdf'
docx_file = 'path/to/sample.docx'
# convert pdf to docx
cv = Converter(pdf_file)
cv.convert(docx_file) # all pages by default
cv.close()
An alternative using ``parse`` method::
from pdf2docx import parse
pdf_file = '/path/to/sample.pdf'
docx_file = 'path/to/sample.docx'
# convert pdf to docx
parse(pdf_file, docx_file)
Example 2: convert specified pages
----------------------------------------
* Specify pages range by ``start`` (from the first page if omitted) and
``end`` (to the last page if omitted)::
# convert from the second page to the end (by default)
cv.convert(docx_file, start=1)
# convert from the first page (by default) to the third (end=3, excluded)
cv.convert(docx_file, end=3)
# convert from the second page and the third
cv.convert(docx_file, start=1, end=3)
* Alternatively, set separate pages by ``pages``::
# convert the first, third and 5th pages
cv.convert(docx_file, pages=[0,2,4])
.. note::
Refer to :py:meth:`~pdf2docx.converter.Converter.convert` for detailed description
on the input arguments.
Example 3: multi-Processing
--------------------------------
Turn on multi-processing with default count of CPU::
cv.convert(docx_file, multi_processing=True)
Specify the count of CPUs::
cv.convert(docx_file, multi_processing=True, cpu_count=4)
.. note::
Multi-processing works for continuous pages specified by ``start`` and ``end`` only.
Example 4: convert encrypted pdf
---------------------------------------
Provide ``password`` to open and convert password protected pdf::
cv = Converter(pdf_file, password)
cv.convert(docx_file)
cv.close()
pdf2docx-0.5.8/doc/quickstart.gui.rst 0000664 0000000 0000000 00000000322 14553521277 0017521 0 ustar 00root root 0000000 0000000 Graphic User Interface
===========================
Thanks @JoHnTsIm providing a ``tkinter`` based user interface.
To launch the GUI::
$ pdf2docx gui
.. image:: https://z3.ax1x.com/2021/05/30/2ZYiUs.png pdf2docx-0.5.8/doc/quickstart.rst 0000664 0000000 0000000 00000000354 14553521277 0016743 0 ustar 00root root 0000000 0000000 Quickstart
=============
``pdf2docx`` can be used as either a Python library or a CLI tool. In addition, it has a simple GUI.
.. toctree::
:maxdepth: 1
quickstart.convert
quickstart.table
quickstart.cli
quickstart.gui pdf2docx-0.5.8/doc/quickstart.table.rst 0000664 0000000 0000000 00000001351 14553521277 0020027 0 ustar 00root root 0000000 0000000 Extract table
======================
::
from pdf2docx import Converter
pdf_file = '/path/to/sample.pdf'
cv = Converter(pdf_file)
tables = cv.extract_tables(start=0, end=1)
cv.close()
for table in tables:
print(table)
The output may look like::
...
[['Input ', None, None, None, None, None],
['Description A ', 'mm ', '30.34 ', '35.30 ', '19.30 ', '80.21 '],
['Description B ', '1.00 ', '5.95 ', '6.16 ', '16.48 ', '48.81 '],
['Description C ', '1.00 ', '0.98 ', '0.94 ', '1.03 ', '0.32 '],
['Description D ', 'kg ', '0.84 ', '0.53 ', '0.52 ', '0.33 '],
['Description E ', '1.00 ', '0.15 ', None, None, None],
['Description F ', '1.00 ', '0.86 ', '0.37 ', '0.78 ', '0.01 ']] pdf2docx-0.5.8/doc/requirements.txt 0000664 0000000 0000000 00000000151 14553521277 0017276 0 ustar 00root root 0000000 0000000 pdf2docx
rst2pdf
# define sphinx versioning
sphinx==5.3.0
autodoc
sphinx_rtd_theme
sphinxcontrib.apidoc
pdf2docx-0.5.8/doc/techdoc.rst 0000664 0000000 0000000 00000002624 14553521277 0016164 0 ustar 00root root 0000000 0000000 Technical Documentation
===========================
PDF文件遵循一定的格式规范,`PyMuPDF `_ 提供了便利的解析函数,
用于获取页面元素例如文本和形状及其位置。然后,基于元素间的相对位置关系解析内容,例如将“横纵线条
围绕着文本”解析为“表格”,将“文本下方的一条横线”解析为“文本下划线”。最后,借助
`python-docx `_ 将解析结果重建为docx格式的Word文档。
以下分篇介绍提取PDF页面数据、解析和重建docx过程中的具体细节:
- 提取文本图片和形状_
- 解析页面布局_
- 解析表格_
- 解析段落_
.. _提取文本图片和形状: https://dothinking.github.io/2020-07-14-pdf2docx%E5%BC%80%E5%8F%91%E6%A6%82%E8%A6%81%EF%BC%9A%E6%8F%90%E5%8F%96%E6%96%87%E6%9C%AC%E3%80%81%E5%9B%BE%E7%89%87%E5%92%8C%E5%BD%A2%E7%8A%B6/
.. _解析页面布局: https://dothinking.github.io/2021-05-30-pdf2docx%E5%BC%80%E5%8F%91%E6%A6%82%E8%A6%81%EF%BC%9A%E8%A7%A3%E6%9E%90%E9%A1%B5%E9%9D%A2%E5%B8%83%E5%B1%80/
.. _解析表格: https://dothinking.github.io/2020-08-15-pdf2docx%E5%BC%80%E5%8F%91%E6%A6%82%E8%A6%81%EF%BC%9A%E8%A7%A3%E6%9E%90%E8%A1%A8%E6%A0%BC/
.. _解析段落: https://dothinking.github.io/2020-08-27-pdf2docx%E5%BC%80%E5%8F%91%E6%A6%82%E8%A6%81%EF%BC%9A%E8%A7%A3%E6%9E%90%E6%AE%B5%E8%90%BD/ pdf2docx-0.5.8/pdf2docx/ 0000775 0000000 0000000 00000000000 14553521277 0014761 5 ustar 00root root 0000000 0000000 pdf2docx-0.5.8/pdf2docx/__init__.py 0000664 0000000 0000000 00000000124 14553521277 0017067 0 ustar 00root root 0000000 0000000 from .converter import Converter
from .page.Page import Page
from .main import parse pdf2docx-0.5.8/pdf2docx/common/ 0000775 0000000 0000000 00000000000 14553521277 0016251 5 ustar 00root root 0000000 0000000 pdf2docx-0.5.8/pdf2docx/common/Block.py 0000664 0000000 0000000 00000011020 14553521277 0017647 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
'''Base class for text/image/table blocks.
'''
from .share import BlockType, TextAlignment
from .Element import Element
class Block(Element):
'''Base class for text/image/table blocks.
Attributes:
raw (dict): initialize object from raw properties.
parent (optional): parent object that this block belongs to.
'''
def __init__(self, raw:dict=None, parent=None):
self._type = BlockType.UNDEFINED
# horizontal spacing
if raw is None: raw = {}
self.alignment = self._get_alignment(raw.get('alignment', 0))
self.left_space = raw.get('left_space', 0.0)
self.right_space = raw.get('right_space', 0.0)
self.first_line_space = raw.get('first_line_space', 0.0)
# RELATIVE position of tab stops
self.tab_stops = raw.get('tab_stops', [])
# vertical spacing
self.before_space = raw.get('before_space', 0.0)
self.after_space = raw.get('after_space', 0.0)
self.line_space = raw.get('line_space', 0.0)
self.line_space_type = raw.get('line_space_type', 1) # 0-exactly, 1-relatively
super().__init__(raw, parent)
@property
def is_text_block(self):
'''Whether test block.'''
return self._type==BlockType.TEXT
@property
def is_inline_image_block(self):
'''Whether inline image block.'''
return self._type==BlockType.IMAGE
@property
def is_float_image_block(self):
'''Whether float image block.'''
return self._type==BlockType.FLOAT_IMAGE
@property
def is_image_block(self):
'''Whether inline or float image block.'''
return self.is_inline_image_block or self.is_float_image_block
@property
def is_text_image_block(self):
'''Whether text block or inline image block.'''
return self.is_text_block or self.is_inline_image_block
@property
def is_lattice_table_block(self):
'''Whether lattice table (explicit table borders) block.'''
return self._type==BlockType.LATTICE_TABLE
@property
def is_stream_table_block(self):
'''Whether stream table (implied by table content) block.'''
return self._type==BlockType.STREAM_TABLE
@property
def is_table_block(self):
'''Whether table (lattice or stream) block.'''
return self.is_lattice_table_block or self.is_stream_table_block
def set_text_block(self):
'''Set block type.'''
self._type = BlockType.TEXT
def set_inline_image_block(self):
'''Set block type.'''
self._type = BlockType.IMAGE
def set_float_image_block(self):
'''Set block type.'''
self._type = BlockType.FLOAT_IMAGE
def set_lattice_table_block(self):
'''Set block type.'''
self._type = BlockType.LATTICE_TABLE
def set_stream_table_block(self):
'''Set block type.'''
self._type = BlockType.STREAM_TABLE
def _get_alignment(self, mode:int):
for t in TextAlignment:
if t.value==mode:
return t
return TextAlignment.LEFT
def parse_horizontal_spacing(self, bbox, *args):
"""Set left alignment, and calculate left space.
Override by :obj:`pdf2docx.text.TextBlock`.
Args:
bbox (fitz.rect): boundary box of this block.
"""
# NOTE: in PyMuPDF CS, horizontal text direction is same with positive x-axis,
# while vertical text is on the contrary, so use f = -1 here
idx, f = (0, 1.0) if self.is_horizontal_text else (3, -1.0)
self.alignment = TextAlignment.LEFT
self.left_space = (self.bbox[idx] - bbox[idx]) * f
def store(self):
'''Store attributes in json format.'''
res = super().store()
res.update({
'type' : self._type.value,
'alignment' : self.alignment.value,
'left_space' : self.left_space,
'right_space' : self.right_space,
'first_line_space' : self.first_line_space,
'before_space' : self.before_space,
'after_space' : self.after_space,
'line_space' : self.line_space,
'line_space_type' : self.line_space_type,
'tab_stops' : self.tab_stops
})
return res
def make_docx(self, *args, **kwargs):
"""Create associated docx element.
Raises:
NotImplementedError
"""
raise NotImplementedError pdf2docx-0.5.8/pdf2docx/common/Collection.py 0000664 0000000 0000000 00000030344 14553521277 0020722 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
'''A group of instances, e.g. Blocks, Lines, Spans, Shapes.
'''
import fitz
from .Element import Element
from .share import (IText, TextDirection)
from .algorithm import (solve_rects_intersection, graph_bfs)
class BaseCollection:
'''Base collection representing a list of instances.'''
def __init__(self, instances:list=None, parent=None):
'''Init collection from a list of instances.'''
self._parent = parent
self._instances = []
self.extend(instances or []) # Note to exclude empty instance by default
def __getitem__(self, idx):
try:
instances = self._instances[idx]
except IndexError:
msg = f'Collection index {idx} out of range.'
raise IndexError(msg)
else:
return instances
def __iter__(self): return (instance for instance in self._instances)
def __len__(self): return len(self._instances)
@property
def parent(self): return self._parent
@property
def bbox(self):
'''bbox of combined collection.'''
rect = fitz.Rect()
for instance in self._instances:
rect |= instance.bbox
return fitz.Rect([round(x,1) for x in rect]) # NOTE: round to avoid digital error
def append(self, instance):
if not instance: return
self._instances.append(instance)
def extend(self, instances:list):
if not instances: return
for instance in instances: self.append(instance)
def reset(self, instances:list=None):
"""Reset instances list.
Args:
instances (list, optional): reset to target instances. Defaults to None.
Returns:
BaseCollection: self
"""
self._instances = []
self.extend(instances or [])
return self
def store(self):
'''Store attributes in json format.'''
return [ instance.store() for instance in self._instances ]
def restore(self, *args, **kwargs):
'''Construct Collection from a list of dict.'''
raise NotImplementedError
class Collection(BaseCollection, IText):
'''Collection of instance focusing on grouping and sorting elements.'''
@property
def text_direction(self):
'''Get text direction. All instances must have same text direction.'''
res = set(instance.text_direction for instance in self._instances)
return list(res)[0] if len(res)==1 else TextDirection.MIX
def group(self, fun):
"""Group instances according to user defined criterion.
Args:
fun (function): with 2 arguments representing 2 instances (Element) and return bool.
Returns:
list: a list of grouped ``Collection`` instances.
Examples 1::
# group instances intersected with each other
fun = lambda a,b: a.bbox & b.bbox
Examples 2::
# group instances aligned horizontally
fun = lambda a,b: a.horizontally_aligned_with(b)
.. note::
It's equal to a GRAPH searching problem, build adjacent list, and then search graph
to find all connected components.
"""
# build adjacent list:
# the i-th item is a set of indexes, which connected to the i-th instance.
# NOTE: O(n^2) method, but it's acceptable (~0.2s) when n<1000 which is satisfied by page blocks
num = len(self._instances)
index_groups = [set() for i in range(num)] # type: list[set]
for i, instance in enumerate(self._instances):
# connections of current instance to all instances after it
for j in range(i+1, num):
if fun(instance, self._instances[j]):
index_groups[i].add(j)
index_groups[j].add(i)
# search graph -> grouped index of instance
groups = graph_bfs(index_groups)
groups = [self.__class__([self._instances[i] for i in group]) for group in groups]
return groups
def group_by_connectivity(self, dx:float, dy:float):
"""Collect connected instances into same group.
Args:
dx (float): x-tolerances to define connectivity
dy (float): y-tolerances to define connectivity
Returns:
list: a list of grouped ``Collection`` instances.
.. note::
* It's equal to a GRAPH traversing problem, which the critical point in
building the adjacent list, especially a large number of vertex (paths).
* Checking intersections between paths is actually a Rectangle-Intersection
problem, studied already in many literatures.
"""
# build the graph -> adjacent list:
# the i-th item is a set of indexes, which connected to the i-th instance
num = len(self._instances)
index_groups = [set() for _ in range(num)] # type: list[set]
# solve rectangle intersection problem
i_rect_x, i = [], 0
d_rect = (-dx, -dy, dx, dy)
for rect in self._instances:
points = [a+b for a,b in zip(rect.bbox, d_rect)] # consider tolerance
i_rect_x.append((i, points, points[0]))
i_rect_x.append((i+1, points, points[2]))
i += 2
i_rect_x.sort(key=lambda item: item[-1])
solve_rects_intersection(i_rect_x, 2*num, index_groups)
# search graph -> grouped index of instance
groups = graph_bfs(index_groups)
groups = [self.__class__([self._instances[i] for i in group]) for group in groups]
return groups
def group_by_columns(self, factor:float=0.0, sorted:bool=True, text_direction:bool=False):
'''Group elements into columns based on the bbox.'''
# split in columns
fun = lambda a,b: a.vertically_align_with(b, factor=factor, text_direction=text_direction)
groups = self.group(fun)
# increase in x-direction if sort
if sorted:
idx = 3 if text_direction and self.is_vertical_text else 0
groups.sort(key=lambda group: group.bbox[idx])
return groups
def group_by_rows(self, factor:float=0.0, sorted:bool=True, text_direction:bool=False):
'''Group elements into rows based on the bbox.'''
# split in rows
fun = lambda a,b: a.horizontally_align_with(b, factor=factor, text_direction=text_direction)
groups = self.group(fun)
# increase in y-direction if sort
if sorted:
idx = 0 if text_direction and self.is_vertical_text else 1
groups.sort(key=lambda group: group.bbox[idx])
return groups
def group_by_physical_rows(self, sorted:bool=False, text_direction:bool=False):
'''Group lines into physical rows.'''
fun = lambda a,b: a.in_same_row(b)
groups = self.group(fun)
# increase in y-direction if sort
if sorted:
idx = 0 if text_direction and self.is_vertical_text else 1
groups.sort(key=lambda group: group.bbox[idx])
return groups
def sort_in_reading_order(self):
'''Sort collection instances in reading order (considering text direction), e.g.
for normal reading direction: from top to bottom, from left to right.
'''
if self.is_horizontal_text:
self._instances.sort(key=lambda e: (e.bbox.y0, e.bbox.x0, e.bbox.x1))
else:
self._instances.sort(key=lambda e: (e.bbox.x0, e.bbox.y1, e.bbox.y0))
return self
def sort_in_line_order(self):
'''Sort collection instances in a physical with text direction considered, e.g.
for normal reading direction: from left to right.
'''
if not self.is_vertical_text:
self._instances.sort(key=lambda e: (e.bbox.x0, e.bbox.y0, e.bbox.x1))
else:
self._instances.sort(key=lambda e: (e.bbox.y1, e.bbox.x0, e.bbox.y0))
return self
def sort_in_reading_order_plus(self):
'''Sort instances in reading order, especially for instances in same row. Taking
natural reading direction for example: reading order for rows, from left to right
for instances in row. In the following example, A comes before B::
+-----------+
+---------+ | |
| A | | B |
+---------+ +-----------+
Steps:
* Sort elements in reading order, i.e. from top to bottom, from left to right.
* Group elements in row.
* Sort elements in row: from left to right.
'''
instances = []
for row in self.group_by_physical_rows(sorted=True, text_direction=True):
row.sort_in_line_order()
instances.extend(row)
self.reset(instances)
class ElementCollection(Collection):
'''Collection of ``Element`` instances.'''
def _update_bbox(self, e:Element):
'''Update parent bbox.'''
if not self._parent is None: # Note: `if self._parent` does not work here
self._parent.union_bbox(e)
def append(self, e:Element):
"""Append an instance, update parent's bbox accordingly and set the parent of the added instance.
Args:
e (Element): instance to append.
"""
if not e: return
self._instances.append(e)
self._update_bbox(e)
# set parent
if not self._parent is None: e.parent = self._parent
def insert(self, nth:int, e:Element):
"""Insert a Element and update parent's bbox accordingly.
Args:
nth (int): the position to insert.
e (Element): the instance to insert.
"""
if not e: return
self._instances.insert(nth, e)
self._update_bbox(e)
e.parent = self._parent # set parent
def pop(self, nth:int):
"""Delete the ``nth`` instance.
Args:
nth (int): the position to remove.
Returns:
Collection: the removed instance.
"""
return self._instances.pop(nth)
def is_flow_layout(self, line_separate_threshold:float, cell_layout=False):
'''Whether contained elements are in flow layout or not.'''
# float layout if vertical text but not cell layout, since vertical text
# will be simulated with stream table
if not cell_layout and self.is_vertical_text:
return False
# flow layout if single column only
if len(self)<=1: return True
if len(self.group_by_columns())>1: return False
# group in physical row and check distance between lines
idx0, idx1 = (0, 2) if self.is_horizontal_text else (3, 1)
for row in self.group_by_physical_rows(text_direction=True):
for i in range(1, len(row)):
dis = abs(row[i].bbox[idx0]-row[i-1].bbox[idx1])
if dis >= line_separate_threshold: return False
return True
def contained_in_bbox(self, bbox):
'''Filter instances contained in target bbox.
Args:
bbox (fitz.Rect): target boundary box.
'''
instances = list(filter(
lambda e: bbox.contains(e.bbox), self._instances))
return self.__class__(instances)
def split_with_intersection(self, bbox:fitz.Rect, threshold:float=1e-3):
"""Split instances into two groups: one intersects with ``bbox``, the other not.
Args:
bbox (fitz.Rect): target rect box.
threshold (float): It's intersected when the overlap rate exceeds this threshold. Defaults to 0.
Returns:
tuple: two group in original class type.
"""
intersections, no_intersections = [], []
for instance in self._instances:
# A contains B => A & B = B
intersection = instance.bbox & bbox
if intersection.is_empty:
no_intersections.append(instance)
else:
factor = round(intersection.get_area()/instance.bbox.get_area(), 2)
if factor >= threshold:
intersections.append(instance)
else:
no_intersections.append(instance)
return self.__class__(intersections), self.__class__(no_intersections)
pdf2docx-0.5.8/pdf2docx/common/Element.py 0000664 0000000 0000000 00000025153 14553521277 0020222 0 ustar 00root root 0000000 0000000 '''Object with a bounding box, e.g. Block, Line, Span.
Based on ``PyMuPDF``, the coordinates (e.g. bbox of ``page.get_text('rawdict')``) are generally
provided relative to the un-rotated page; while this ``pdf2docx`` library works under real page
coordinate system, i.e. with rotation considered. So, any instances created by this Class are
always applied a rotation matrix automatically.
Therefore, the bbox parameter used to create ``Element`` instance MUST be relative to un-rotated
CS. If final coordinates are provided, should update it after creating an empty object::
Element().update_bbox(final_bbox)
.. note::
An exception is ``page.get_drawings()``, the coordinates are converted to real page CS already.
'''
import copy
import fitz
from .share import IText
from . import constants
class Element(IText):
'''Boundary box with attribute in fitz.Rect type.'''
# all coordinates are related to un-rotated page in PyMuPDF
# e.g. Matrix(0.0, 1.0, -1.0, 0.0, 842.0, 0.0)
ROTATION_MATRIX = fitz.Matrix(0.0) # rotation angle = 0 degree by default
@classmethod
def set_rotation_matrix(cls, rotation_matrix):
"""Set global rotation matrix.
Args:
Rotation_matrix (fitz.Matrix): target matrix
"""
if rotation_matrix and isinstance(rotation_matrix, fitz.Matrix):
cls.ROTATION_MATRIX = rotation_matrix
@classmethod
def pure_rotation_matrix(cls):
'''Pure rotation matrix used for calculating text direction after rotation.'''
a,b,c,d,e,f = cls.ROTATION_MATRIX
return fitz.Matrix(a,b,c,d,0,0)
def __init__(self, raw:dict=None, parent=None):
''' Initialize Element and convert to the real (rotation considered) page CS.'''
self.bbox = fitz.Rect() # type: fitz.Rect
self._parent = parent # type: Element
# NOTE: Any coordinates provided in raw is in original page CS
# (without considering page rotation).
if 'bbox' in (raw or {}):
rect = fitz.Rect(raw['bbox']) * Element.ROTATION_MATRIX
self.update_bbox(rect)
def __bool__(self):
'''Real object when bbox is defined.'''
# NOTE inconsistent results of fitz.Rect for different version of pymupdf, e.g.,
# a = fitz.Rect(3,3,2,2)
# bool(a) a.get_area() a.is_empty
# pymupdf 1.23.5 True 1.0 True
# pymupdf 1.23.8 True 0.0 True
# bool(fitz.Rect())==False
# NOTE: do not use `return not self.bbox.is_empty` here
return bool(self.bbox)
def __repr__(self): return f'{self.__class__.__name__}({tuple(self.bbox)})'
# ------------------------------------------------
# parent element
# ------------------------------------------------
@property
def parent(self): return self._parent
@parent.setter
def parent(self, parent): self._parent = parent
# ------------------------------------------------
# bbox operations
# ------------------------------------------------
def copy(self):
'''make a deep copy.'''
# NOTE: can't serialize data because parent is an Object,
# so set it None in advance.
parent, self.parent = self._parent, None
obj = copy.deepcopy(self)
self._parent = parent # set back parent
return obj
def get_expand_bbox(self, dt:float):
"""Get expanded bbox with margin in both x- and y- direction.
Args:
dt (float): Expanding margin.
Returns:
fitz.Rect: Expanded bbox.
.. note::
This method creates a new bbox, rather than changing the bbox of itself.
"""
return self.bbox + (-dt, -dt, dt, dt)
def update_bbox(self, rect):
'''Update current bbox to specified ``rect``.
Args:
rect (fitz.Rect or list): bbox-like ``(x0, y0, x1, y1)``,
in real page CS (with rotation considered).
'''
self.bbox = fitz.Rect([round(x,1) for x in rect])
return self
def union_bbox(self, e):
"""Update current bbox to the union with specified Element.
Args:
e (Element): The target to get union
Returns:
Element: self
"""
return self.update_bbox(self.bbox | e.bbox)
# --------------------------------------------
# location relationship to other Element instance
# --------------------------------------------
def contains(self, e:'Element', threshold:float=1.0):
"""Whether given element is contained in this instance, with margin considered.
Args:
e (Element): Target element
threshold (float, optional): Intersection rate.
Defaults to 1.0. The larger, the stricter.
Returns:
bool: [description]
"""
S = e.bbox.get_area()
if not S: return False
# it's not practical to set a general threshold to consider the margin, so two steps:
# - set a coarse but acceptable area threshold,
# - check the length in main direction strictly
# A contains B => A & B = B
intersection = self.bbox & e.bbox
factor = round(intersection.get_area()/S, 2)
if factor= self.bbox.height:
return self.bbox.width+constants.MINOR_DIST >= e.bbox.width
return self.bbox.height+constants.MINOR_DIST >= e.bbox.height
def get_main_bbox(self, e, threshold:float=0.95):
"""If the intersection with ``e`` exceeds the threshold, return the union of
these two elements; else return None.
Args:
e (Element): Target element.
threshold (float, optional): Intersection rate. Defaults to 0.95.
Returns:
fitz.Rect: Union bbox or None.
"""
bbox_1 = self.bbox
bbox_2 = e.bbox if hasattr(e, 'bbox') else fitz.Rect(e)
# areas
b = bbox_1 & bbox_2
if b.is_empty: return None # no intersection
# Note: if bbox_1 and bbox_2 intersects with only an edge, b is not empty but b.get_area()=0
# so give a small value when they're intersected but the area is zero
a1, a2, a = bbox_1.get_area(), bbox_2.get_area(), b.get_area()
factor = a/min(a1,a2) if a else 1e-6
return bbox_1 | bbox_2 if factor >= threshold else None
def vertically_align_with(self, e, factor:float=0.0, text_direction:bool=True):
'''Check whether two Element instances have enough intersection in vertical direction,
i.e. perpendicular to reading direction.
Args:
e (Element): Object to check with
factor (float, optional): Threshold of overlap ratio, the larger it is, the higher
probability the two bbox-es are aligned.
text_direction (bool, optional): Consider text direction or not. True by default.
Returns:
bool: [description]
Examples::
+--------------+
| |
+--------------+
L1
+-------------------+
| |
+-------------------+
L2
An enough intersection is defined based on the minimum width of two boxes::
L1+L2-L>factor*min(L1,L2)
'''
if not e or not bool(self): return False
# text direction
idx = 1 if text_direction and self.is_vertical_text else 0
L1 = self.bbox[idx+2]-self.bbox[idx]
L2 = e.bbox[idx+2]-e.bbox[idx]
L = max(self.bbox[idx+2], e.bbox[idx+2]) - min(self.bbox[idx], e.bbox[idx])
eps = 1e-3 # tolerant
return L1+L2-L+eps >= factor*min(L1,L2)
def horizontally_align_with(self, e, factor:float=0.0, text_direction:bool=True):
'''Check whether two Element instances have enough intersection in horizontal direction,
i.e. along the reading direction.
Args:
e (Element): Element to check with
factor (float, optional): threshold of overlap ratio, the larger it is, the higher
probability the two bbox-es are aligned.
text_direction (bool, optional): consider text direction or not. True by default.
Examples::
+--------------+
| | L1 +--------------------+
+--------------+ | | L2
+--------------------+
An enough intersection is defined based on the minimum width of two boxes::
L1+L2-L>factor*min(L1,L2)
'''
if not e or not bool(self): return False
# text direction
idx = 0 if text_direction and self.is_vertical_text else 1
L1 = self.bbox[idx+2]-self.bbox[idx]
L2 = e.bbox[idx+2]-e.bbox[idx]
L = max(self.bbox[idx+2], e.bbox[idx+2]) - min(self.bbox[idx], e.bbox[idx])
eps = 1e-3 # tolerant
return L1+L2-L+eps >= factor*min(L1,L2)
def in_same_row(self, e):
"""Check whether in same row/line with specified Element instance.
With text direction considered.
Taking horizontal text as an example:
* yes: the bottom edge of each box is lower than the centerline of the other one;
* otherwise, not in same row.
Args:
e (Element): Target object.
.. note::
The difference to method ``horizontally_align_with``: they may not in same line, though
aligned horizontally.
"""
if not e or self.is_horizontal_text != e.is_horizontal_text:
return False
# normal reading direction by default
idx = 1 if self.is_horizontal_text else 0
c1 = (self.bbox[idx] + self.bbox[idx+2]) / 2.0
c2 = (e.bbox[idx] + e.bbox[idx+2]) / 2.0
res = c1<=e.bbox[idx+2] and c2<=self.bbox[idx+2] # Note y direction under PyMuPDF context
return res
# ------------------------------------------------
# others
# ------------------------------------------------
def store(self):
'''Store properties in raw dict.'''
return { 'bbox': tuple(x for x in self.bbox) }
def plot(self, page, stroke:tuple=(0,0,0), width:float=0.5, fill:tuple=None, dashes:str=None):
'''Plot bbox in PDF page for debug purpose.'''
page.draw_rect(self.bbox,
color=stroke,
fill=fill,
width=width,
dashes=dashes,
overlay=False,
fill_opacity=0.5)
pdf2docx-0.5.8/pdf2docx/common/__init__.py 0000664 0000000 0000000 00000000000 14553521277 0020350 0 ustar 00root root 0000000 0000000 pdf2docx-0.5.8/pdf2docx/common/algorithm.py 0000664 0000000 0000000 00000035720 14553521277 0020620 0 ustar 00root root 0000000 0000000 from collections import deque
import numpy as np
import cv2 as cv
# -------------------------------------------------------------------------------------------
# Intersection area of two iso-oriented rectangles
# -------------------------------------------------------------------------------------------
def get_area(bbox_1:tuple, bbox_2:tuple):
x0, y0, x1, y1 = bbox_1
u0, v0, u1, v1 = bbox_2
# width of intersected area
w = (x1-x0) + (u1-u0) - (max(x1, u1)-min(x0, u0))
if w<=0: return 0
# height of intersected area
h = (y1-y0) + (v1-v0) - (max(y1, v1)-min(y0, v0))
if h<=0: return 0
return w*h
# -------------------------------------------------------------------------------------------
# Breadth First Search method for graph
# -------------------------------------------------------------------------------------------
def graph_bfs(graph):
'''Breadth First Search graph (may be disconnected graph).
Args:
graph (list): GRAPH represented by adjacent list, [set(1,2,3), set(...), ...]
Returns:
list: A list of connected components
'''
# search graph
# NOTE: generally a disconnected graph
counted_indexes = set() # type: set[int]
groups = []
for i in range(len(graph)):
if i in counted_indexes: continue
# connected component starts...
indexes = set(_graph_bfs_from_node(graph, i))
groups.append(indexes)
counted_indexes.update(indexes)
return groups
def _graph_bfs_from_node(graph, start):
'''Breadth First Search connected graph with start node.
Args:
graph (list): GRAPH represented by adjacent list, [set(1,2,3), set(...), ...].
start (int): Index of any start vertex.
'''
search_queue = deque()
searched = set()
search_queue.append(start)
while search_queue:
cur_node = search_queue.popleft()
if cur_node in searched: continue
yield cur_node
searched.add(cur_node)
for node in graph[cur_node]:
search_queue.append(node)
# -------------------------------------------------------------------------------------------
# Implementation of solving Rectangle-Intersection Problem according to algorithm proposed in
# paper titled "A Rectangle-Intersection Algorithm with Limited Resource Requirements".
# https://ieeexplore.ieee.org/document/5578313
#
# - Input
# The rectangle is represented by its corner points, (x0, y0, x1, y1)
#
# - Output
# The output is an Adjacent List of each rect, which could be used to initialize a GRAPH.
# -------------------------------------------------------------------------------------------
# procedure report(S, n)
# 1 Let V be the list of x-coordinates of the 2n vertical edges in S sorted in non-decreasing order.
# 2 Let H be the list of n y-intervals corresponding to the bottom and top y-coordinates of each rectangle.
# 3 Sort the elements of H in non-decreasing order by their bottom y-coordinates.
# 4 Call procedure detect(V, H, 2n).
def solve_rects_intersection(V:list, num:int, index_groups:list):
'''Implementation of solving Rectangle-Intersection Problem.
Performance::
O(nlog n + k) time and O(n) space, where k is the count of intersection pairs.
Args:
V (list): Rectangle-related x-edges data, [(index, Rect, x), (...), ...].
num (int): Count of V instances, equal to len(V).
index_groups (list): Target adjacent list for connectivity between rects.
Procedure ``detect(V, H, m)``::
if m < 2 then return else
- let V1 be the first ⌊m/2⌋ and let V2 be the rest of the vertical edges in V in the sorted order;
- let S11 and S22 be the set of rectangles represented only in V1 and V2 but not spanning V2 and V1, respectively;
- let S12 be the set of rectangles represented only in V1 and spanning V2;
- let S21 be the set of rectangles represented only in V2 and spanning V1
- let H1 and H2 be the list of y-intervals corresponding to the elements of V1 and V2 respectively
- stab(S12, S22); stab(S21, S11); stab(S12, S21)
- detect(V1, H1, ⌊m/2⌋); detect(V2, H2, m − ⌊m/2⌋)
'''
if num < 2: return
# start/end points of left/right intervals
center_pos = int(num/2.0)
X0, X, X1 = V[0][-1], V[center_pos-1][-1], V[-1][-1]
# split into two groups
left = V[0:center_pos]
right = V[center_pos:]
# filter rects according to their position to each intervals
S11 = list(filter( lambda item: item[1][2]<=X, left ))
S12 = list(filter( lambda item: item[1][2]>=X1, left ))
S22 = list(filter( lambda item: item[1][0]>X, right ))
S21 = list(filter( lambda item: item[1][0]<=X0, right ))
# intersection in x-direction is fulfilled, so check y-direction further
_stab(S12, S22, index_groups)
_stab(S21, S11, index_groups)
_stab(S12, S21, index_groups)
# recursive process
solve_rects_intersection(left, center_pos, index_groups)
solve_rects_intersection(right, num-center_pos, index_groups)
def _stab(S1:list, S2:list, index_groups:list):
'''Check interval intersection in y-direction.
Procedure ``stab(A, B)``::
i := 1; j := 1
while i ≤ |A| and j ≤ |B|
if ai.y0 < bj.y0 then
k := j
while k ≤ |B| and bk.y0 < ai.y1
reportPair(air, bks)
k := k + 1
i := i + 1
else
k := i
while k ≤ |A| and ak.y0 < bj.y1
reportPair(bjs, akr)
k := k + 1
j := j + 1
'''
if not S1 or not S2: return
# sort
S1.sort(key=lambda item: item[1][1])
S2.sort(key=lambda item: item[1][1])
i, j = 0, 0
while i 1
for c0, c1 in zip(arr_x0, arr_x1):
y_arr = arr[r0:r1, c0:c1]
top_left = (x0+c0, y0+r0)
xy_cut(y_arr, top_left, res, min_w, min_h, min_dx, min_dy)
# do xy-cut recursively
res = []
xy_cut(arr=img_binary, top_left=(0, 0), res=res,
min_w=min_w, min_h=min_h, min_dx=min_dx, min_dy=min_dy)
return res
def _split_projection_profile(arr_values:np.array, min_value:float, min_gap:float):
'''Split projection profile:
```
┌──┐
arr_values │ │ ┌─┐───
┌──┐ │ │ │ │ |
│ │ │ │ ┌───┐ │ │min_value
│ │<- min_gap ->│ │ │ │ │ │ |
────┴──┴─────────────┴──┴─┴───┴─┴─┴─┴───
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
```
Args:
arr_values (np.array): 1-d array representing the projection profile.
min_value (float): Ignore the profile if `arr_value` is less than `min_value`.
min_gap (float): Ignore the gap if less than this value.
Returns:
tuple: Start indexes and end indexes of split groups.
'''
# all indexes with projection height exceeding the threshold
arr_index = np.where(arr_values>min_value)[0]
if not len(arr_index): return
# find zero intervals between adjacent projections
# | | ||
# ||||<- zero-interval -> |||||
arr_diff = arr_index[1:] - arr_index[0:-1]
arr_diff_index = np.where(arr_diff>min_gap)[0]
arr_zero_intvl_start = arr_index[arr_diff_index]
arr_zero_intvl_end = arr_index[arr_diff_index+1]
# convert to index of projection range:
# the start index of zero interval is the end index of projection
arr_start = np.insert(arr_zero_intvl_end, 0, arr_index[0])
arr_end = np.append(arr_zero_intvl_start, arr_index[-1])
arr_end += 1 # end index will be excluded as index slice
return arr_start, arr_end
def inner_contours(img_binary:np.array, bbox:tuple, min_w:float, min_h:float):
'''Inner contours of current region, especially level 2 contours of the default opencv tree hirerachy.
Args:
img_binary (np.array): Binarized image with interesting region (255) and empty region (0).
bbox (tuple): The external bbox.
min_w (float): Ignore contours if the bbox width is less than this value.
min_h (float): Ignore contours if the bbox height is less than this value.
Returns:
list: A list of bbox-es of inner contours.
'''
# find both external and inner contours of current region
x0, y0, x1, y1 = bbox
arr = np.zeros(img_binary.shape, dtype=np.uint8)
arr[y0:y1, x0:x1] = img_binary[y0:y1, x0:x1]
contours, hierarchy = cv.findContours(arr, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
# check first three level contours:
# * level-0, i.e. table bbox
# * level-1, i.e. cell bbox
# * level-2, i.e. region within cell
# NOTE: only one dimension, i.e. the second, to be decided, so the
# return value of np.where is a len==1 tuple
level_0 = np.where(hierarchy[0,:,3]==-1)[0]
level_1 = np.where(np.isin(hierarchy[0,:,3], level_0))[0]
level_2 = np.where(np.isin(hierarchy[0,:,3], level_1))[0]
# In general, we focus on only level 2, but considering edge case: level 2 contours
# might be counted as level 1 incorrectly, e.g. test/samples/demo-table-close-underline.pdf.
# So, get first the concerned level 1 contours, i.e. those contained by other level 1 contour.
def contains(bbox1, bbox2):
x0, y0, x1, y1 = bbox1
u0, v0, u1, v1 = bbox2
return u0>=x0 and v0>=y0 and u1<=x1 and v1<=y1
level_1_bbox_list, res_level_1, res = [], [], []
for i in level_1:
x, y, w, h = cv.boundingRect(contours[i])
if w