Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Image to PDF Converter and PDF Merger | Python

#1
Image to PDF Converter and PDF Merger | Python

<div>
<div class="kk-star-ratings kksr-auto kksr-align-left kksr-valign-top" data-payload='{&quot;align&quot;:&quot;left&quot;,&quot;id&quot;:&quot;1051108&quot;,&quot;slug&quot;:&quot;default&quot;,&quot;valign&quot;:&quot;top&quot;,&quot;ignore&quot;:&quot;&quot;,&quot;reference&quot;:&quot;auto&quot;,&quot;class&quot;:&quot;&quot;,&quot;count&quot;:&quot;0&quot;,&quot;legendonly&quot;:&quot;&quot;,&quot;readonly&quot;:&quot;&quot;,&quot;score&quot;:&quot;0&quot;,&quot;starsonly&quot;:&quot;&quot;,&quot;best&quot;:&quot;5&quot;,&quot;gap&quot;:&quot;5&quot;,&quot;greet&quot;:&quot;Rate this post&quot;,&quot;legend&quot;:&quot;0\/5 - (0 votes)&quot;,&quot;size&quot;:&quot;24&quot;,&quot;width&quot;:&quot;0&quot;,&quot;_legend&quot;:&quot;{score}\/{best} - ({count} {votes})&quot;,&quot;font_factor&quot;:&quot;1.25&quot;}'>
<div class="kksr-stars">
<div class="kksr-stars-inactive">
<div class="kksr-star" data-star="1" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="2" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="3" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="4" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="5" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
<div class="kksr-stars-active" style="width: 0px;">
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
</div>
<div class="kksr-legend" style="font-size: 19.2px;"> <span class="kksr-muted">Rate this post</span> </div>
</p></div>
<figure class="wp-block-image size-full is-style-default"><img loading="lazy" decoding="async" width="965" height="549" src="https://blog.finxter.com/wp-content/uploads/2023/01/image-114.png" alt="" class="wp-image-1051170" srcset="https://blog.finxter.com/wp-content/uploads/2023/01/image-114.png 965w, https://blog.finxter.com/wp-content/uplo...00x171.png 300w, https://blog.finxter.com/wp-content/uplo...68x437.png 768w" sizes="(max-width: 965px) 100vw, 965px" /></figure>
<h2>Project Description</h2>
<p>In my university days, I often came across scenarios where I needed to convert image files to PDF files and then merge all the PDF files together to submit my assignments. Now, you will find tons of online resources to convert images to PDFs and also merge PDFs. But the big question is – “Are they all safe?” </p>
<p>That is why I decided to take things into my hands and create a script that would not only convert my image files to PDFs but also merge those PDFs together. That is exactly what I will be demonstrating in this project. </p>
<p>So we will be performing a couple of tasks in this project –</p>
<ul>
<li>Convert all the images to PDF files.</li>
<li>Merge all the converted PDF files into a single PDF file. </li>
</ul>
<p>So, without further delay, let us dive into our project.</p>
<h2>Step 1: Install and Import the Necessary Libraries</h2>
<p>We will need to install a couple of libraries that will help us to complete our task. The first library is the PIL (Python Imaging Library) which is Python’s &nbsp;de facto image processing package. To install it, open your terminal and type the following command: </p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">pip install pillow</pre>
<p> The next library that you need to install is known as <a href="https://pypi.org/project/PyPDF2/">PyPDF2</a>. PyPDF2 is a free and open-source pure-python PDF library capable of splitting,&nbsp;merging,&nbsp;cropping<a href="https://pypdf2.readthedocs.io/en/stable/user/cropping-and-transforming.html">,</a> and transforming&nbsp;the pages of PDF files. It can also add custom data, viewing options, and&nbsp;passwords&nbsp;to PDF files. PyPDF2 can&nbsp;retrieve text&nbsp;and&nbsp;metadata&nbsp;from PDFs as well. To install it, open your terminal and type the following command: </p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">pip install PyPDF2</pre>
</p>
<p>Once you have installed the necessary libraries, go ahead and import them into your script. Note that you will also need to import the <a rel="noreferrer noopener" href="https://blog.finxter.com/exploring-pythons-os-module/" target="_blank">os</a> module to open the required files from their respective paths.</p>
<p><strong>Code:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import os
from PIL import Image
from PyPDF2 import PdfMerger</pre>
<h2>Step 2: Fetch the Path of the Source and Destination Directories</h2>
<p>You need to fetch the path of the source folder where you have stored the images and also the path of the destination folder where you will save the PDF files. </p>
<p><strong>Code:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">img_dir = './image_files'
pdf_dir = './pdf_files'</pre>
<p>In my case, I have created two different directories by the name ‘<em>image_files</em>‘ and ‘<em>pdf_files</em>‘ within my project folder and then stored them in two different variables which I will be using later on in my code.</p>
<h2>Step 3: Converting Image to PDF</h2>
<p>We are all set to create the image to PDF converter function that will convert an image into a PDF. The idea is to navigate the image folder with the help of the <code>os.listdir</code> method and grab all the image files within it. If an image file is located we open it up using the <code>Image</code> module of the <code>PIL</code> package.</p>
<p>You then have to specify the color profile of the PDF and you can mention that to be <code>RGB</code>. You can do this with the help of the <code>convert</code> function. Then you can directly save this converted RGB image to the destination folder in the PDF format using the <code>save</code> method. To save it as a PDF file you can pass the extension as .pdf as <code>'{0}.pdf'.format(file.split('.')[-2])</code>. That’s it. This should convert all the images in the images folder to individual PDF files. </p>
<p><strong>Code:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def img_to_pdf_converter(): for file in os.listdir(img_dir): if file.split('.')[-1] in ('png', 'jpg', 'jpeg'): image = Image.open(os.path.join(img_dir, file)) coneverted_image = image.convert('RGB') coneverted_image.save(os.path.join(pdf_dir, '{0}.pdf'.format(file.split('.')[-2]))) print("PDF Created!")</pre>
<h2>Step 4: Merge the PDFs</h2>
<p>Once you have all the PDF versions of the image files, you can then merge them using the PyPDF2 library. Go ahead and create an empty list that will store the names of all the PDFs that were created from the image files. Then create an instance of the <code>PdfMerger</code> class that resides with the <code>PyPDF2</code> module. </p>
<p>Then navigate the PDF folder and fetch all the PDF files and merge them together using a for loop and within the for loop use the append method to merge them together. As simple as that! </p>
<p><strong>Code:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def merger(): pdfs = [] merge = PdfMerger() for file in os.listdir(pdf_dir): pdfs.append(pdf_dir+"/"+file) for pdf in pdfs: merge.append(pdf) merge.write('merged_pdf.pdf') merge.close() print("PDFs Merged!")</pre>
<h2>Putting It All Together</h2>
<p>We have successfully created both functions to convert images to PDFs and then merge them. All that remains to be done is to call these functions and your script should work like a charm. <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f609.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> </p>
<p>Finally, when you put everything together, this is how the complete script looks like –</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import os
img_dir = './image_files'
pdf_dir = './pdf_files' def img_to_pdf_converter(): from PIL import Image for file in os.listdir(img_dir): if file.split('.')[-1] in ('png', 'jpg', 'jpeg'): image = Image.open(os.path.join(img_dir, file)) coneverted_image = image.convert('RGB') coneverted_image.save(os.path.join(pdf_dir, '{0}.pdf'.format(file.split('.')[-2]))) print("PDF Created!") def merger(): pdfs = [] from PyPDF2 import PdfMerger merge = PdfMerger() for file in os.listdir(pdf_dir): pdfs.append(pdf_dir+"/"+file) for pdf in pdfs: merge.append(pdf) merge.write('merged_pdf.pdf') merge.close() print("PDFs Merged!") img_to_pdf_converter()
merger()</pre>
<h2>Conclusion </h2>
<p>Woohoo!!! We have successfully completed our fun project, and now we do not need the aid of any third-party application to convert our images to PDFs or merge our PDFs. I hope this project added some value and helped you in your coding quest. Stay tuned and&nbsp;<strong><a rel="noreferrer noopener" href="https://blog.finxter.com/subscribe/" target="_blank">subscribe</a></strong>&nbsp;for more interesting projects and tutorials.</p>
<hr class="wp-block-separator has-alpha-channel-opacity" />
</div>


https://www.sickgaming.net/blog/2023/01/...er-python/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016