I am trying to add two images in docx file.
Images should be one left side one right side.
After using this below code the image position is working like left and right as I want but they are not on the same line I want.
One is up and others are under that image.
I have tried the WD_ALIGN_PARAGRAPH.RIGHT but I am not getting the result I want.
## Image for Left Side
my_img = document.add_picture(i,width=Inches(0.8),height=Inches(0.8))
last_paragraph = document.paragraphs[-1]
last_paragraph.alignment = WD_ALIGN_PARAGRAPH.LEFT
## Image for Right Side
my_img2 = document.add_picture(i,width=Inches(0.8),height=Inches(0.8))
last_paragraph = document.paragraphs[-1]
last_paragraph.alignment = WD_ALIGN_PARAGRAPH.RIGHT
Please help me, I want both images on same line like two images together with little space between them.
Use Run.add_picture() instead of Paragraph.add_picture(). This will allow multiple images in the same paragraph, which, if they both fit within the page margins, will result in side-by-side images:
paragraph = document.add_paragraph()
run = paragraph.add_run()
run.add_picture(...)
run_2 = paragraph.add_run()
run_2.add_picture(...)
As far as alignment is concerned, when using paragraphs, inserting tabs is probably most reliable. The other alternative is to add a table and place the images in side-by-side cells.
Related
I wrote a little script which shall blank out the lower half of a PDF document. The document itself shall remain the same size, but the lower half shall be just white.
(This is to remove the "instructions" part from parcel labels of German parcel comanies like DHL and Hermes.)
To do this, I take the PDF page, adjust the Mediabox, and then merge this page onto a new, blank page.
Fortunately, this works as intended with the PDFs I need it for. However, I also tried a few other PDFs and for some, it just does not work. It copies over the complete PDF. This happens for example, when my code is given this file: https://www.veeam.com/veeam_backup_product_overview_ds.pdf
Here is the code:
import pypdf # PyPDF2, 3 and 4 are deprecated. PyPDF is currently in active development
reader = pypdf.PdfReader(source_filename)
writer = pypdf.PdfWriter()
# get first page
page = reader.pages[0]
# create new page
new_page = pypdf.PageObject.create_blank_page( None, width = page.mediabox.width, height = page.mediabox.height )
# crop original
page.mediabox.bottom = ( page.mediabox.top - page.mediabox.bottom ) / 2 + page.mediabox.bottom
# merge original into empty new page
new_page.merge_page( page )
writer.add_page(new_page)
with open(output_file, "wb") as fp:
writer.write(fp)
Can anyone explain why it does not work sometimes?
I need to replace a K words with K other words for every PDF file I have within a certain path file location and on top of this I need to replace every logo with another logo. I have around 1000 PDF files, and so I do not want to use Adobe Acrobat and edit 1 file at a time. How can I start this?
Replacing words seems at least doable as long as there is a decent PDF reader one can access through Python ( Note I want to do this task in Python ), however replacing an image might be more difficult. I will most likely have to find the dimension of the current image and resize the image being used to replace the current image dynamically, whilst the program runs through these PDF files.
Hi, so I've written down some code regarding this:
from pikepdf import Pdf, PdfImage, Name
import os
import glob
from PIL import Image
import zlib
example = Pdf.open(r'...\Likelihood.pdf')
PagesWithImages = []
ImageCodesForPages = []
# Grab all the pages and all the images in every page.
for i in example.pages:
if len(list(i.images.keys())) >= 1:
PagesWithImages.append(i)
ImageCodesForPages.append(list(i.images.keys()))
pdfImages = []
for i,j in zip(PagesWithImages, ImageCodesForPages):
for x in j:
pdfImages.append(i.images[x])
# Replace every single page using random image, ensure that the dimensions remain the same?
for i in pdfImages:
pdfimage = PdfImage(i)
rawimage = pdfimage.obj
im = Image.open(r'...\panda.jpg')
pillowimage = pdfimage.as_pil_image()
print(pillowimage.height)
print(pillowimage.width)
im = im.resize((pillowimage.width, pillowimage.height))
im.show()
rawimage.write(zlib.compress(im.tobytes()), filter=Name("/FlateDecode"))
rawimage.ColorSpace = Name("/DeviceRGB")
So just one problem, it doesn't actually replace anything. If you're wondering why and how I wrote this code I actually got it from this documentation:
https://buildmedia.readthedocs.org/media/pdf/pikepdf/latest/pikepdf.pdf
Start at Page 53
I essentially put all the pdfImages into a list, as 1 page can have multiple images. In conjunction with this, the last for loop essentially tries to replace all these images whilst maintaining the same width and height size. Also note, the file path names I changed here and it definitely is not the issue.
Again Thank You
I have figured out what I was doing wrong. So for anyone that wants to actually replace an image with another image in place on a PDF file what you do is:
from pikepdf import Pdf, PdfImage, Name
from PIL import Image
import zlib
example = Pdf.open(filepath, allow_overwriting_input=True)
PagesWithImages = []
ImageCodesForPages = []
# Grab all the pages and all the images in every page.
for i in example.pages:
imagelists = list(i.images.keys())
if len(imagelists) >= 1:
for x in imagelists:
rawimage = i.images[x]
pdfimage = PdfImage(rawimage)
rawimage = pdfimage.obj
pillowimage = pdfimage.as_pil_image()
im = Image.open(imagePath)
im = im.resize((pillowimage.width, pillowimage.height))
rawimage.write(zlib.compress(im.tobytes()), filter=Name("/FlateDecode"))
rawimage.ColorSpace = Name("/DeviceRGB")
rawimage.Width, rawimage.Height = pillowimage.width, pillowimage.height
example.save()
Essentially, I changed the arguements in the first line, such that I specify that I can overwrite. In conjunction, I also added the last line which actually allows me to save.
I have a bunch of image like this one:
Where the yellow box are contents of different profiles (text), where each section is divided by the dashed lines (no the straight lines). So what I need is to split the image into multiple single images by the dashed lines. So far I have tried a lot of python and cv2 examples with the Hough Line Transform but none of my attempts works in the detection.
Following #efirvida's comment, here's a very basic approach on how to do it.
What it does is simply checking whether each line of pixels in the given picture is equal in value to the first line containing a dashed line, and then crop the picture to split it into multiple pictures...
# import image/array manipulation packages
import cv2
import numpy as np
# read image with OpenCV 2
img = cv2.imread("path/to/file/z4Xje.jpg")
# identify one line of pixels that has dashes
dashes = img[761,:,:]
# check where to split the picture and store that information
splits = [0]
for i in range(img.shape[0]):
# np.allclose allows you to have small differences between dashed lines
if np.allclose(img[i,:,:], dashes):
splits.append(i)
# add last split (height of picture)
splits.append(img.shape[0])
# write each cropped picture to your desired directory
for j in range(len(splits)-1):
new_img = img[splits[j]:splits[j+1],:]
cv2.imwrite("/path/to/export/"+str(j)+".jpg", new_img)
It quite certainly isn't a perfect solution but I hope it gives you clues on how to improve your current algorithm!
It gave me these pictures for the one you provided:
first split
second split
third split
I am writing a macro for LibreOffice Writer in Python.
I need to insert several images in one document, one after another with minimal space inbetween them.
The folowing code inserts all the images in the same area and all of them are overlapped.
I need to advance the cursor below the inserted image everytime a new image is inserted.
I have tried the cursor.gotoEnd(), cursor.goDown() and other such methods but none seem to work.
How do I make this work?
def InsertAll():
desktop = XSCRIPTCONTEXT.getDesktop()
doc=desktop.loadComponentFromURL('private:factory/swriter','_blank',0,())
text = doc.getText()
cursor = text.createTextCursor()
file_list = glob.glob('/path/of/your/dir/*.png')
for f in file_list:
img = doc.createInstance('com.sun.star.text.TextGraphicObject')
img.GraphicURL = 'file://' + f
text.insertTextContent(cursor, img, False)
cursor.gotoEnd(False) <- doesnt advance the cursor downwards
return None
Insert a paragraph break after each image:
from com.sun.star.text.ControlCharacter import PARAGRAPH_BREAK
text.insertTextContent(cursor, img, False)
text.insertControlCharacter(cursor, PARAGRAPH_BREAK, False)
cursor.gotoEnd(False)
This will separate the images... by a paragraph
Andrew's book is a basic source for solving many OpenOffice scripting problems: +1
I'm trying to cut a section from one image and paste it into another. I'm using the following code:
img1 = Image.open("Img1.png")
img2 = Image.open("Img2.png")
cut = img2.crop((31, 0, 47, 15))
cut.save("cut.png")
img1.paste(cut, (150,300))
img1.save("NewImg1.png")
When I look at cut.png I see the right part cut out. However when it's pasted into img1, the resulting image just has a black box where the pasted section should be.
I suspect this may more be an issue with my images than the code, (both were created in Paint.NET, saved with default options) but I don't really know where to look right now to figure out the problem.