How can I, using Python (2.7) get the contents of the Mac clipboard. Is there a better way than making a wrapper around pbpaste?
Thanks!
PyObjC is the way to go:
#!/usr/bin/python
from AppKit import NSPasteboard, NSStringPboardType
pb = NSPasteboard.generalPasteboard()
pbstring = pb.stringForType_(NSStringPboardType)
print u"Pastboard string: %s".encode("utf-8") % repr(pbstring)
This only supports text and will return None otherwise. You can extend it to support other data types as well, see NSPastboard Class Reference.
Have you looked at the xerox module?
It is supposed to support windows, OS X and Linux
Usage is as follows:
xerox.copy(u'some string')
And to paste:
>>> xerox.paste()
u'some string'
If you have installed pandas, you can use the function in pandas as follows:
from pandas.io.clipboard import clipboard_get
text = clipboard_get()
The problem with the xerox module and most code samples I've found for "get the contents of the Mac clipboard" is that they return plain text only. They don't support hyperlinks, styles, and such, so they're not really able to access the full contents provided by apps like Microsoft Word and Google Chrome.
Standing on the shoulders of others, I finally figured out how to do this. The resulting richxerox module is available on PyPI and Bitbucket.
Though this question is old, I'm leaving breadcrumbs here because I consistently re-found this page via Google while searching for the answer.
Do you know PyObjC? I guess you could use it to write a Py wrapper which interfaces with NSPasteboard. This might be more "elegant" than shelling out to pbpaste.
You can grab the clipboard (and the screen) with PIL/Pillow on a Mac like this:
from PIL import ImageGrab, Image
# Grab clipboard and save to disk
clip = ImageGrab.grabclipboard()
clip.save("clip.png")
Just for completeness, you can grab the screen like this:
screen = ImageGrab.grab()
# That results in this:
# <PIL.PngImagePlugin.PngImageFile image mode=RGBA size=5120x2880 at 0x110BB7748>
# Save to disk
screen.save("screen.png")
Related
I want to export a ppt slide as an png format image through pptx python.
I have gone through this solution using win32com but facing error as com_error: (-2147221005, 'Invalid class string', None, None) while running win32com.client.Dispatch("PowerPoint.Application")
I have also tried using pptx_tools.utils.save_pptx_as_png, but it is asking Comptype module needed to save PNGs. and I don't find any comptype module in Python. I have installed comtype module but it is throwing an syntax error while importing.
Please let me know any efficient way to export pptx slide as image
As you've tagged this with "python-pptx" I have to tell you python-pptx can't do it.
You'd have to do it by automating the Powerpoint application itself. (Sorry, I don't know how to do that.)
After I try many times, I corrected some places and it runs fine:
Import module:
import win32com.client
Your path 1 (pptx file):
"/ddd/xxx/yyy/file.pptx"
Your path 2 (output file):
"/ddd/xxx/yyy/file.jpg"
I am looking to convert a xml file to an image (ideally a png file) using a python script. I have not found much from my online research. I am trying to use PIL. From this post on StackOverflow I was able to find this code:
from PIL import Image
import ImageFont, ImageDraw
image = Image.new("RGBA", (288,432), (255,255,255))
usr_font = ImageFont.truetype("resources/HelveticaNeueLight.ttf", 25)
d_usr = ImageDraw.Draw(image)
d_usr = d_usr.text((105,280), "MYTEXT",(0,0,0), font=usr_font)
But I do not quite understand what's happening. I tried to replace "MYTEXT" with the actual xml file content and it did not work.
I am basically looking for any solution (ideally using PIL, but it can be another module for python). I came close using imgkit:
import imgkit
imgkit.from_file('example_IN.xml','example_OUT.png')
which returns a png file. The resolution of the image is terrible though, and it lies within a very large white rectangle. I may be missing something. I know you can modify options for imgkit, but I have no idea what modifications to bring, even after checking the documentation. Any help would be deeply appreciated.
Thank you so much!
Best regards.
I had a go in pyvips:
#!/usr/bin/env python3
import sys
import pyvips
from xml.sax.saxutils import escape
# load first arg as a string
txt = open(sys.argv[1], "r").read()
# pyvips allows pango markup in strings -- you can write stuff like
# text("hello <i>sailor!</i>")
# so we need to escape < > & in the text file
txt = escape(txt)
img = pyvips.Image.text(txt)
# save to second arg
img.write_to_file(sys.argv[2])
You can run it like this:
./txt2img.py vari.ws x.png
To make this:
It's pretty quick -- that took 300ms to run on this modest laptop.
The text method has a lot of options if you want higher res, to change the alignment, wrap lines at some limit, change the font, etc. etc.
https://libvips.github.io/libvips/API/current/libvips-create.html#vips-text
The solution suggested above by jcuppit using pyvips definitely works and is quick. I found another solution to make my previous code above work using imgkit (it is slower, I am giving it here just for reference): the resolution of the output image was bad. If this happens, width and height can be changed in the options (this is an easy fix I had missed):
import imgkit
options = {
'width' : 600,
'height' : 600
}
imgkit.from_file('example_IN.xml','example_OUT.png', options=options)
And that will convert a xml file into a png file as well.
On my Ubuntu server I've installed the python-qrtools package (which makes use of zbar) using sudo apt-get install python-qrtools to decode images of QR-codes and bar-codes in Python like this:
>>> qr = qrtools.QR()
>>> qr.decode('the_qrcode_or_barcode_image.jpg')
True
>>> print qr.data
Hello! :)
This works perfectly fine.
I now want to store this data and regenerate the image at a later point in time. But the problem is that I don't know whether the original image was a QR-code or some type of bar-code. I checked all properties of the qr object, but none of them seems to give me the type of Encoding Style (QR/bar/other).
In this SO thread it is described that ZBar does give back the type of Encoding Style, but it only gives an example in Objective-C, plus I'm not sure if this is actually an answer to what I am looking for.
Does anybody know how I can find out the type of Encoding Style (so QR-code/BAR-code/other) in Python (preferably using the python-qrtools package)? And if not in Python, are there any Linux command line tools which can find this out? All tips are welcome!
Looking at the source of qrtools, I cannot see any way to get the type but there is a zbar python lib, based on the scan_image example, the code below seems to do what you want:
import zbar
import Image
scanner = zbar.ImageScanner()
scanner.parse_config('enable')
img = Image.open("br.png").convert('L')
width, height = img.size
stream = zbar.Image(width, height, 'Y800', img.tostring())
scanner.scan(stream)
for symbol in stream:
print 'decoded', symbol.type, 'symbol', '"%s"' % symbol.data
Using a random barcode I grabbed from the net:
decoded UPCA symbol "123456789012"
Using this qr code outputs:
decoded QRCODE symbol "http://www.reichmann-racing.de"
Im trying to read a file's format so I can correctly assign a new name to it and write it to disk, but when the Image.open() is on the image, I cannot write the image to disk. So for example :
This works:
>>>file = open('708864.jpg')
>>> open('lala.jpeg', 'w').write(file.read())
But, this doesn't
>>>import Image
>>>im = Image.open('708864.jpg')
>>> im.format
>>> open('lala.jpeg', 'w').write(file.read())
It creates a corrupted file (lala.jpeg) which is unable to be opened by any software.
I'm suspecting the culprit is the Image.open(). And after trying to locate an Image.close() statement, I was unable to find one. How would you "close" this image, so I can still write it to disk?
As suggested in my comment, im.save('lala.jpg') is the way to go.
For all the other fun methods on an Image object, you can look at the documentation.
Some workaround, it is just idea:
import Image
import StringIO
file = open('/home/mrok/1.jpg')
output = StringIO.StringIO(file.read())
im = Image.open('/home/mrok/1.jpg')
im.format
open('/home/mrok/2.jpg', 'w').write(output.getvalue())
output.close()
As said in a comment, I ended up using a function I never knew about before, Image.save() , which quickly solves my problem.
I'm creating some SVGs in batches and need to convert those to a PDF document for printing. I've been trying to use svglib and its svg2rlg method but I've just discovered that it's absolutely appalling at preserving the vector graphics in my document. It can barely position text correctly.
My dynamically-generated SVG is well formed and I've tested svglib on the raw input to make sure it's not a problem I'm introducing.
So what are my options past svglib and ReportLab? It either has to be free or very cheap as we're already out of budget on the project this is part of. We can't afford the 1k/year fee for ReportLab Plus.
I'm using Python but at this stage, I'm happy as long as it runs on our Ubuntu server.
Edit: Tested Prince. Better but it's still ignoring half the document.
I use inkscape for this. In your django view do like:
from subprocess import Popen
x = Popen(['/usr/bin/inkscape', your_svg_input, \
'--export-pdf=%s' % your_pdf_output])
try:
waitForResponse(x)
except OSError, e:
return False
def waitForResponse(x):
out, err = x.communicate()
if x.returncode < 0:
r = "Popen returncode: " + str(x.returncode)
raise OSError(r)
You may need to pass as parameters to inkscape all the font files you refer to in your .svg, so keep that in mind if your text does not appear correctly on the .pdf output.
CairoSVG is the one I am using:
import cairosvg
cairosvg.svg2pdf(url='image.svg', write_to='image.pdf')
rst2pdf uses reportlab for generating PDFs. It can use inkscape and pdfrw for reading PDFs.
pdfrw itself has some examples that show reading PDFs and using reportlab to output.
Addressing the comment by Martin below (I can edit this answer, but do not have the reputation to comment on a comment on it...):
reportlab knows nothing about SVG files. Some tools, like svg2rlg, attempt to recreate an SVG image into a PDF by drawing them into the reportlab canvas. But you can do this a different way with pdfrw -- if you can use another tool to convert the SVG file into a PDF image, then pdfrw can take that converted PDF, and add it as a form XObject into the PDF that you are generating with reportlab. As far as reportlab is concerned, it is really no different than placing a JPEG image.
Some tools will do terrible things to your SVG files (rasterizing them, for example). In my experience, inkscape usually does a pretty good job, and leaves them in a vector format. You can even do this headless, e.g. "inkscape my.svg -A my.pdf".
The entire reason I wrote pdfrw in the first place was for this exact use-case -- being able to reuse vector images in new PDFs created by reportlab.
Just to let you know and for the future issue, I find a solution for this problem:
# I only install svg2rlg, not svglib (svg2rlg is inside svglib as well)
import svg2rlg
# Import of the canvas
from reportlab.pdfgen import canvas
# Import of the renderer (image part)
from reportlab.graphics import renderPDF
rlg = svg2rlg.svg2rlg("your_img.svg")
c = canvas.Canvas("example.pdf")
c.setTitle("my_title_we_dont_care")
# Generation of the first page
# You have a last option on this function,
# about the boundary but you can leave it as default.
renderPDF.draw(rlg, c, 80, 740 - rlg.height)
renderPDF.draw(rlg, c, 60, 540 - rlg.height)
c.showPage()
# Generation of the second page
renderPDF.draw(rlg, c, 50, 740 - rlg.height)
c.showPage()
# Save
c.save()
Enjoy a bit with the position (80, 740 - h), it is only the position.
If the code doesn't work, you can look at in the render's reportlab library.
You have a function in reportlab to create directly a pdf from your image:
renderPDF.drawToFile(rlg, "example.pdf", "title")
You can open it and read it. It is not very complicated. This code come from this function.