1633664443
Tìm hiểu cách hợp nhất hai hoặc nhiều tệp PDF thành một tệp PDF duy nhất bằng thư viện PyPDF4 bằng Python
Mục tiêu chính của việc hợp nhất các tệp PDF là để quản lý tệp thích hợp, để lưu trữ, in hàng loạt hoặc kết hợp các biểu dữ liệu, sách điện tử và báo cáo. Bạn chắc chắn cần một công cụ hiệu quả để hợp nhất các tệp PDF nhỏ thành một tệp PDF duy nhất.
Hướng dẫn này nhằm chỉ cho bạn cách hợp nhất danh sách các tệp PDF thành một tệp PDF duy nhất bằng ngôn ngữ lập trình Python. PDF kết hợp có thể bao gồm các dấu trang để cải thiện điều hướng trong đó mọi dấu trang được liên kết với nội dung của một trong các tệp PDF đã nhập.
Chúng tôi sẽ sử dụng thư viện PyPDF4 cho mục đích này. PyPDF4 là một thư viện PDF thuần python có khả năng chia nhỏ, hợp nhất với nhau, cắt và chuyển đổi các trang của tệp PDF. Nó cũng có thể thêm dữ liệu tùy chỉnh, tùy chọn xem và mật khẩu vào tệp PDF. Nó có thể lấy văn bản và siêu dữ liệu từ các tệp PDF cũng như hợp nhất toàn bộ các tệp với nhau.
Hãy cài đặt nó:
$ pip install PyPDF4==1.27.0
Nhập các thư viện:
#Import Libraries
from PyPDF4 import PdfFileMerger
import os,argparse
Hãy xác định chức năng cốt lõi của chúng tôi:
def merge_pdfs(input_files: list, page_range: tuple, output_file: str, bookmark: bool = True):
"""
Merge a list of PDF files and save the combined result into the `output_file`.
`page_range` to select a range of pages (behaving like Python's range() function) from the input files
e.g (0,2) -> First 2 pages
e.g (0,6,2) -> pages 1,3,5
bookmark -> add bookmarks to the output file to navigate directly to the input file section within the output file.
"""
# strict = False -> To ignore PdfReadError - Illegal Character error
merger = PdfFileMerger(strict=False)
for input_file in input_files:
bookmark_name = os.path.splitext(os.path.basename(input_file))[0] if bookmark else None
# pages To control which pages are appended from a particular file.
merger.append(fileobj=open(input_file, 'rb'), pages=page_range, bookmark=bookmark_name)
# Insert the pdf at specific page
merger.write(fileobj=open(output_file, 'wb'))
merger.close()
Vì vậy, trước tiên chúng ta tạo một PDFFileMerger
đối tượng và sau đó lặp lại input_files
từ đầu vào. Sau đó, đối với mỗi tệp PDF đầu vào, chúng tôi xác định dấu trang nếu được yêu cầu tùy thuộc vào bookmark
biến và thêm nó vào đối tượng hợp nhất có tính đến page_range
đã chọn.
Tiếp theo, chúng tôi sử dụng append()
phương pháp từ hợp nhất để thêm tệp PDF của chúng tôi.
Cuối cùng, chúng tôi viết tệp PDF đầu ra và đóng đối tượng.
Bây giờ hãy thêm một hàm để phân tích cú pháp các đối số dòng lệnh:
def parse_args():
"""Get user command line parameters"""
parser = argparse.ArgumentParser(description="Available Options")
parser.add_argument('-i', '--input_files', dest='input_files', nargs='*',
type=str, required=True, help="Enter the path of the files to process")
parser.add_argument('-p', '--page_range', dest='page_range', nargs='*',
help="Enter the pages to consider e.g.: (0,2) -> First 2 pages")
parser.add_argument('-o', '--output_file', dest='output_file',
required=True, type=str, help="Enter a valid output file")
parser.add_argument('-b', '--bookmark', dest='bookmark', default=True, type=lambda x: (
str(x).lower() in ['true', '1', 'yes']), help="Bookmark resulting file")
# To Porse The Command Line Arguments
args = vars(parser.parse_args())
# To Display The Command Line Arguments
print("## Command Arguments #################################################")
print("\n".join("{}:{}".format(i, j) for i, j in args.items()))
print("######################################################################")
return args
Bây giờ, hãy sử dụng các hàm đã được xác định trước đó trong mã chính của chúng ta:
if __name__ == "__main__":
# Parsing command line arguments entered by user
args = parse_args()
# convert a single str to a list
input_files = [str(x) for x in args['input_files'][0].split(',')]
page_range = None
if args['page_range']:
page_range = tuple(int(x) for x in args['page_range'][0].split(','))
# call the main function
merge_pdfs(
input_files=input_files, page_range=page_range,
output_file=args['output_file'], bookmark=args['bookmark']
)
Được rồi, chúng ta đã viết xong mã, hãy cùng kiểm tra:
$ python pdf_merger.py --help
Đầu ra:
usage: pdf_merger.py [-h] -i [INPUT_FILES [INPUT_FILES ...]] [-p [PAGE_RANGE [PAGE_RANGE ...]]] -o OUTPUT_FILE [-b BOOKMARK]
Available Options
optional arguments:
-h, --help show this help message and exit
-i [INPUT_FILES [INPUT_FILES ...]], --input_files [INPUT_FILES [INPUT_FILES ...]]
Enter the path of the files to process
-p [PAGE_RANGE [PAGE_RANGE ...]], --page_range [PAGE_RANGE [PAGE_RANGE ...]]
Enter the pages to consider e.g.: (0,2) -> First 2 pages
-o OUTPUT_FILE, --output_file OUTPUT_FILE
Enter a valid output file
-b BOOKMARK, --bookmark BOOKMARK
Bookmark resulting file
Dưới đây là một ví dụ về việc hợp nhất hai tệp PDF thành một:
$ python pdf_merger.py -i bert-paper.pdf,letter.pdf -o combined.pdf
Bạn cần phân tách các tệp PDF đầu vào bằng dấu phẩy (,)
trong -i
đối số và bạn không được thêm bất kỳ khoảng trắng nào.
Một combined.pdf
tệp mới xuất hiện trong thư mục hiện tại chứa cả hai tệp PDF đầu vào, đầu ra là:
## Command Arguments #################################################
input_files:['bert-paper.pdf,letter.pdf']
page_range:None
output_file:combined.pdf
bookmark:True
######################################################################
Đảm bảo rằng bạn sử dụng đúng thứ tự của các tệp đầu vào khi truyền -i
đối số.
Tôi hy vọng mã này sẽ giúp bạn hợp nhất các tệp PDF một cách dễ dàng và không cần bên thứ ba hoặc các công cụ trực tuyến, việc sử dụng Python để thực hiện các tác vụ như vậy sẽ thuận tiện hơn.
Kiểm tra mã đầy đủ ở đây .
Nguồn: https://www.thepythoncode.com
#python #pdf
1619510796
Welcome to my Blog, In this article, we will learn python lambda function, Map function, and filter function.
Lambda function in python: Lambda is a one line anonymous function and lambda takes any number of arguments but can only have one expression and python lambda syntax is
Syntax: x = lambda arguments : expression
Now i will show you some python lambda function examples:
#python #anonymous function python #filter function in python #lambda #lambda python 3 #map python #python filter #python filter lambda #python lambda #python lambda examples #python map
1626775355
No programming language is pretty much as diverse as Python. It enables building cutting edge applications effortlessly. Developers are as yet investigating the full capability of end-to-end Python development services in various areas.
By areas, we mean FinTech, HealthTech, InsureTech, Cybersecurity, and that's just the beginning. These are New Economy areas, and Python has the ability to serve every one of them. The vast majority of them require massive computational abilities. Python's code is dynamic and powerful - equipped for taking care of the heavy traffic and substantial algorithmic capacities.
Programming advancement is multidimensional today. Endeavor programming requires an intelligent application with AI and ML capacities. Shopper based applications require information examination to convey a superior client experience. Netflix, Trello, and Amazon are genuine instances of such applications. Python assists with building them effortlessly.
Python can do such numerous things that developers can't discover enough reasons to admire it. Python application development isn't restricted to web and enterprise applications. It is exceptionally adaptable and superb for a wide range of uses.
Robust frameworks
Python is known for its tools and frameworks. There's a structure for everything. Django is helpful for building web applications, venture applications, logical applications, and mathematical processing. Flask is another web improvement framework with no conditions.
Web2Py, CherryPy, and Falcon offer incredible capabilities to customize Python development services. A large portion of them are open-source frameworks that allow quick turn of events.
Simple to read and compose
Python has an improved sentence structure - one that is like the English language. New engineers for Python can undoubtedly understand where they stand in the development process. The simplicity of composing allows quick application building.
The motivation behind building Python, as said by its maker Guido Van Rossum, was to empower even beginner engineers to comprehend the programming language. The simple coding likewise permits developers to roll out speedy improvements without getting confused by pointless subtleties.
Utilized by the best
Alright - Python isn't simply one more programming language. It should have something, which is the reason the business giants use it. Furthermore, that too for different purposes. Developers at Google use Python to assemble framework organization systems, parallel information pusher, code audit, testing and QA, and substantially more. Netflix utilizes Python web development services for its recommendation algorithm and media player.
Massive community support
Python has a steadily developing community that offers enormous help. From amateurs to specialists, there's everybody. There are a lot of instructional exercises, documentation, and guides accessible for Python web development solutions.
Today, numerous universities start with Python, adding to the quantity of individuals in the community. Frequently, Python designers team up on various tasks and help each other with algorithmic, utilitarian, and application critical thinking.
Progressive applications
Python is the greatest supporter of data science, Machine Learning, and Artificial Intelligence at any enterprise software development company. Its utilization cases in cutting edge applications are the most compelling motivation for its prosperity. Python is the second most well known tool after R for data analytics.
The simplicity of getting sorted out, overseeing, and visualizing information through unique libraries makes it ideal for data based applications. TensorFlow for neural networks and OpenCV for computer vision are two of Python's most well known use cases for Machine learning applications.
Thinking about the advances in programming and innovation, Python is a YES for an assorted scope of utilizations. Game development, web application development services, GUI advancement, ML and AI improvement, Enterprise and customer applications - every one of them uses Python to its full potential.
The disadvantages of Python web improvement arrangements are regularly disregarded by developers and organizations because of the advantages it gives. They focus on quality over speed and performance over blunders. That is the reason it's a good idea to utilize Python for building the applications of the future.
#python development services #python development company #python app development #python development #python in web development #python software development
1624428000
The Portable Document Format (PDF) is not a WYSIWYG (What You See is What You Get) format. It was developed to be platform-agnostic, independent of the underlying operating system and rendering engines.
To achieve this, PDF was constructed to be interacted with via something more like a programming language, and relies on a series of instructions and operations to achieve a result. In fact, PDF is based on a scripting language - PostScript, which was the first device-independent Page Description Language.
In this guide, we’ll be using pText - a Python library dedicated to reading, manipulating and generating PDF documents. It offers both a low-level model (allowing you access to the exact coordinates and layout if you choose to use those) and a high-level model (where you can delegate the precise calculations of margins, positions, etc to a layout manager).
We’ll take a look at how to create a PDF invoice in Python using pText.
#python #pdf #creating pdf invoices in python with ptext #creating pdf invoices #pdf invoice #creating pdf invoices in python with ptext
1633664443
Tìm hiểu cách hợp nhất hai hoặc nhiều tệp PDF thành một tệp PDF duy nhất bằng thư viện PyPDF4 bằng Python
Mục tiêu chính của việc hợp nhất các tệp PDF là để quản lý tệp thích hợp, để lưu trữ, in hàng loạt hoặc kết hợp các biểu dữ liệu, sách điện tử và báo cáo. Bạn chắc chắn cần một công cụ hiệu quả để hợp nhất các tệp PDF nhỏ thành một tệp PDF duy nhất.
Hướng dẫn này nhằm chỉ cho bạn cách hợp nhất danh sách các tệp PDF thành một tệp PDF duy nhất bằng ngôn ngữ lập trình Python. PDF kết hợp có thể bao gồm các dấu trang để cải thiện điều hướng trong đó mọi dấu trang được liên kết với nội dung của một trong các tệp PDF đã nhập.
Chúng tôi sẽ sử dụng thư viện PyPDF4 cho mục đích này. PyPDF4 là một thư viện PDF thuần python có khả năng chia nhỏ, hợp nhất với nhau, cắt và chuyển đổi các trang của tệp PDF. Nó cũng có thể thêm dữ liệu tùy chỉnh, tùy chọn xem và mật khẩu vào tệp PDF. Nó có thể lấy văn bản và siêu dữ liệu từ các tệp PDF cũng như hợp nhất toàn bộ các tệp với nhau.
Hãy cài đặt nó:
$ pip install PyPDF4==1.27.0
Nhập các thư viện:
#Import Libraries
from PyPDF4 import PdfFileMerger
import os,argparse
Hãy xác định chức năng cốt lõi của chúng tôi:
def merge_pdfs(input_files: list, page_range: tuple, output_file: str, bookmark: bool = True):
"""
Merge a list of PDF files and save the combined result into the `output_file`.
`page_range` to select a range of pages (behaving like Python's range() function) from the input files
e.g (0,2) -> First 2 pages
e.g (0,6,2) -> pages 1,3,5
bookmark -> add bookmarks to the output file to navigate directly to the input file section within the output file.
"""
# strict = False -> To ignore PdfReadError - Illegal Character error
merger = PdfFileMerger(strict=False)
for input_file in input_files:
bookmark_name = os.path.splitext(os.path.basename(input_file))[0] if bookmark else None
# pages To control which pages are appended from a particular file.
merger.append(fileobj=open(input_file, 'rb'), pages=page_range, bookmark=bookmark_name)
# Insert the pdf at specific page
merger.write(fileobj=open(output_file, 'wb'))
merger.close()
Vì vậy, trước tiên chúng ta tạo một PDFFileMerger
đối tượng và sau đó lặp lại input_files
từ đầu vào. Sau đó, đối với mỗi tệp PDF đầu vào, chúng tôi xác định dấu trang nếu được yêu cầu tùy thuộc vào bookmark
biến và thêm nó vào đối tượng hợp nhất có tính đến page_range
đã chọn.
Tiếp theo, chúng tôi sử dụng append()
phương pháp từ hợp nhất để thêm tệp PDF của chúng tôi.
Cuối cùng, chúng tôi viết tệp PDF đầu ra và đóng đối tượng.
Bây giờ hãy thêm một hàm để phân tích cú pháp các đối số dòng lệnh:
def parse_args():
"""Get user command line parameters"""
parser = argparse.ArgumentParser(description="Available Options")
parser.add_argument('-i', '--input_files', dest='input_files', nargs='*',
type=str, required=True, help="Enter the path of the files to process")
parser.add_argument('-p', '--page_range', dest='page_range', nargs='*',
help="Enter the pages to consider e.g.: (0,2) -> First 2 pages")
parser.add_argument('-o', '--output_file', dest='output_file',
required=True, type=str, help="Enter a valid output file")
parser.add_argument('-b', '--bookmark', dest='bookmark', default=True, type=lambda x: (
str(x).lower() in ['true', '1', 'yes']), help="Bookmark resulting file")
# To Porse The Command Line Arguments
args = vars(parser.parse_args())
# To Display The Command Line Arguments
print("## Command Arguments #################################################")
print("\n".join("{}:{}".format(i, j) for i, j in args.items()))
print("######################################################################")
return args
Bây giờ, hãy sử dụng các hàm đã được xác định trước đó trong mã chính của chúng ta:
if __name__ == "__main__":
# Parsing command line arguments entered by user
args = parse_args()
# convert a single str to a list
input_files = [str(x) for x in args['input_files'][0].split(',')]
page_range = None
if args['page_range']:
page_range = tuple(int(x) for x in args['page_range'][0].split(','))
# call the main function
merge_pdfs(
input_files=input_files, page_range=page_range,
output_file=args['output_file'], bookmark=args['bookmark']
)
Được rồi, chúng ta đã viết xong mã, hãy cùng kiểm tra:
$ python pdf_merger.py --help
Đầu ra:
usage: pdf_merger.py [-h] -i [INPUT_FILES [INPUT_FILES ...]] [-p [PAGE_RANGE [PAGE_RANGE ...]]] -o OUTPUT_FILE [-b BOOKMARK]
Available Options
optional arguments:
-h, --help show this help message and exit
-i [INPUT_FILES [INPUT_FILES ...]], --input_files [INPUT_FILES [INPUT_FILES ...]]
Enter the path of the files to process
-p [PAGE_RANGE [PAGE_RANGE ...]], --page_range [PAGE_RANGE [PAGE_RANGE ...]]
Enter the pages to consider e.g.: (0,2) -> First 2 pages
-o OUTPUT_FILE, --output_file OUTPUT_FILE
Enter a valid output file
-b BOOKMARK, --bookmark BOOKMARK
Bookmark resulting file
Dưới đây là một ví dụ về việc hợp nhất hai tệp PDF thành một:
$ python pdf_merger.py -i bert-paper.pdf,letter.pdf -o combined.pdf
Bạn cần phân tách các tệp PDF đầu vào bằng dấu phẩy (,)
trong -i
đối số và bạn không được thêm bất kỳ khoảng trắng nào.
Một combined.pdf
tệp mới xuất hiện trong thư mục hiện tại chứa cả hai tệp PDF đầu vào, đầu ra là:
## Command Arguments #################################################
input_files:['bert-paper.pdf,letter.pdf']
page_range:None
output_file:combined.pdf
bookmark:True
######################################################################
Đảm bảo rằng bạn sử dụng đúng thứ tự của các tệp đầu vào khi truyền -i
đối số.
Tôi hy vọng mã này sẽ giúp bạn hợp nhất các tệp PDF một cách dễ dàng và không cần bên thứ ba hoặc các công cụ trực tuyến, việc sử dụng Python để thực hiện các tác vụ như vậy sẽ thuận tiện hơn.
Kiểm tra mã đầy đủ ở đây .
Nguồn: https://www.thepythoncode.com
#python #pdf
1602968400
Python is awesome, it’s one of the easiest languages with simple and intuitive syntax but wait, have you ever thought that there might ways to write your python code simpler?
In this tutorial, you’re going to learn a variety of Python tricks that you can use to write your Python code in a more readable and efficient way like a pro.
Swapping value in Python
Instead of creating a temporary variable to hold the value of the one while swapping, you can do this instead
>>> FirstName = "kalebu"
>>> LastName = "Jordan"
>>> FirstName, LastName = LastName, FirstName
>>> print(FirstName, LastName)
('Jordan', 'kalebu')
#python #python-programming #python3 #python-tutorials #learn-python #python-tips #python-skills #python-development