Set font color on only one table row rather than entire document - python-docx

import docx
from docx.api import Document
from docx.shared import RGBColor
if condition:
paragraph = row[2].add_paragraph('Different Text') # Not Blue
else:
blue_paragraph = row[2].add_paragraph('X')
font = blue_paragraph.style.font
font.color.rgb = RGBColor(0x42, 0x24, 0xE9)
The above code is not only making my entire row[2] blue, it is making the entire document blue. How can I set only the 'X' text blue?

In this line:
font = blue_paragraph.style.font
You're selecting the font of what is probably the Normal style, and then setting it to blue in the following line. This explains why the whole document is turning blue; Normal is the default style for all paragraphs in the document.
You either need to create a new style that is blue and apply that to the paragraphs in question, or set the font of the runs of the target text directly.
So something like this would work, but be less optimal in some ways than using a style:
blue_paragraph = row[2].add_paragraph("X")
for run in blue_paragraph.runs:
run.font.color.rgb = RGBColor(0x42, 0x24, 0xE9)
This page in the python-docx documentation describes Word styles in a way you might find helpful.
https://python-docx.readthedocs.io/en/latest/user/styles-understanding.html

Related

How can I put an image on a Matlab uicontrol button?

I have Matlab 2019b, GUI Layout Toolbox 2.3.4 and t all runs on MacOs 14 Mojave.
I want to create button in in a UI that have icons/images instead of text. I have seen here:
https://undocumentedmatlab.com/blog/html-support-in-matlab-uicomponents/
that it is supposed to be possible to use HTML to render the button contents.
So - I try this sample code:
figure('MenuBar','none','Name','GUI-TEST','NumberTitle','off','Position',[200,200,140,90]);
push_btn = uicontrol('Style','PushButton','String','Push','Position',[30,60,80,20],...
'CallBack','disp(''You are pressed a push button'')');
close_btn = uicontrol('Style','PushButton','String','Close','Position',[30,5,80,50],...
'CallBack','close');
icon_file = fullfile(pwd, 'close.png')
str = ['<html><img src="file://' icon_file '"></html>']
set(close_btn,'String',str);
but it leaves me with an empty button.
If I deliberately use a filename that does not correspond to an existing file, I see a broken image icon:
So I am reasonably sure that the basic syntax and file path stuff is correct but the image does not get rendered in the button.
Is there something else I need to do to make this work or is it all just part of Matlab's overwhelming strangeness?
The easiest way to put an image on a uicontrol (and specifically a button), is to use the CData property,
im_orig = imread(icon_file); % Needs to be true color, i.e. MxNx3
im_sized = imresize(im_orig,[80,50]); % size of the button
% str = ['<html><img src="file://' icon_file '"></html>'];
% set(close_btn,'String',str);
set(close_btn,'CData',im_sized);

Python-Docx Is it possible to remove textwrapping around picture?

I´m using run.add_picture() to add a image to my document, but it comes with a 0,30cm spacing around it. I want to remove it so there is no spacing between the text and the image, but I don´t know how to clear this spacing.
Here is the code:
from docx import Document
doc = Document()
doc.add_picture('icon.png')
doc.save('test.docx')
If I understand correctly, you want to insert a floating image instead of an inline one. The code you showed inserts an inline one:
from docx import Document
doc = Document()
doc.add_picture('icon.png')
doc.save('test.docx')
However, if you first create the paragraph you want to insert the picture, you can add it in a specific run:
from docx import Document
doc = Document()
par = doc.add_paragraph('test text 2\n')
r = par.add_run()
r.add_picture(r'icon.png')
r.add_break()
r.add_text('\n continue with text after image.')
doc.save('test.docx')

Python 2.7 Copy and paste hyperlinked text

I am using Python 2.7, Webdriver and Chrome. Manually, I can mouse swipe across text containing a hyperlink on a web page and copy it to the clipboard. How do I do this automatically? I have no issue finding the element containing the hyperlink. I am not trying to find the hyperlink. I am trying to paste it into a web page text box which does not process https://www.python.org/ ">Link within an "a" tag but processes it correctly when pasted from elsewhere i.e. "Link" with embedded href.
Even after OP clarifications, it's still hard to understand the exact issue, so I'll try to cover all possible options :)
Suppose we have an anchor element, like Link
We can find this element in such ways
element = driver.find_element_by_xpath('//a[text()="Link"]')
element = driver.find_element_by_xpath('//a[#href=" python.org "]')
depending on what information we currently know about the element and what exactly we want to scrap.
Also, we can use index of anchor element element = driver.find_elements_by_tag_name('a')[0]
1) To get value of href attribute:
value = element.get_attribute('href')
Output: https://python.org
2) To get value of text node:
value = element.text
Output: "Link"
3) To get complete HTML code of element:
value = element.get_attribute('outerHTML')
Output: Link

Replace picture (from page header)

I have a base .docx for which I need to change the page header / footer image on a case by case basis. I read that python-docx does not yet handle headers/footers but it does handle Pictures.
What I cannot work around is how to replace them.
I found the Pictures in the documents ._package.parts objects as ImagePart, I could even try to identify the image by its partname attribute.
What I could not find in any way is how to replace the image. I tried replacing the ImagePart ._blob and ._image attributes but it makes no difference after saving.
So, what would be the "good" way to replace one Image blob with another one using python-docx? (it is the only change I need to do).
Current code is:
d = Document(docx='basefile.docx')
parts = d._package
for p in parts:
if isinstance(p, docx.parts.image.ImagePart) and p.partname.find('image1.png'):
img = p
break
img._blob = open('newfile.png', 'r').read()
d.save('newfile.docx')
Thanks,
marc
There is no requirement to use python-docx. I found another Python library for messing with docx files called "paradocx" altought it seems a bit abandoned it works for what I need.
python-docx would be preferable as the project seems more healthy so a solution based on it is still desired.
Anyway, here is the paradocx based solution:
from paradocx import Document
from paradocx.headerfooter import HeaderPart
template = 'template.docx'
newimg = open('new_file.png', 'r')
doc = Document.from_file(template)
header = doc.get_parts_by_class(HeaderPart).next()
img = header.related('http://schemas.openxmlformats.org/officeDocument/2006/relationships/image')[0]
img.data = newimg.read()
newimg.close()
doc.save('prueba.docx')

Minimal HTML/CSS to specify distinct color for each character of the text

I need to specify a different color for each character of the text in an HTML page. The text is long and the generated HTML file size should be as small as possible. In other words, the color formatting tags used should be as minimal as possible. How do you suggest to perform this task?
You need to wrap each character in an element, so it seems that the minimal code is like
<a style=color:#123456>x</a>
or alternatively
<font color=#123456>x</font>
for each character x. The codes are of equal length, but in the latter, the number sign '#' can in practice be omitted (it is an error to omit it, but by browser practice and HTML5 drafts, there is error handling that effectively implies the # provided that the value does not constitute a color name known to the browser. This is risky, so I would go for the first alternatively.
If the colors are not in fact all different but may repeat, then the use of
<a class=¿>x</a>
together with CSS definitions like
.¿{color:#123456}
could result in shorter code. You would then need a class name generator; you could keep the class names to single characters, but care would be needed to make sure that the class selectors will conform to CSS syntax.
I can't realy tell if there is a way to do it into CSS
but here is my code in JavaScript
var textID = document.getElementById("text"); // go and take the Text from the ID
var text = textID.innerHTML; // Take the text from the
var toChange = text.split(""); // Separrate each letter into array
var newText = ""; // buffer text
var aClassName = ["red", "green", "blue"]; // class name that you want
var colorNumber = 0; // counter to loop into your class
for (var i=0, ii=toChange.length; i<ii; i++){
if(colorNumber == aClassName.length){ // if you reach the end of your class array
colorNumber = 0; //Set it back to 0
}
// Add between each letter the span with your class
newText += "<span class="+aClassName[colorNumber]+">"+toChange[i]+"<\/span>";
colorNumber++
}
// Output your text into the web
textID.innerHTML = newText;
http://jsfiddle.net/WPSrX/
I am taking the chance of attempting to answer this. This is admittedly not a direct answer, but another way of looking at it that would keep your code to an absolute minimum:
If what you want is a sort of non-intrusive watermark; I would suggest the simplest solution to set opacity on the text, and a text-shadow in the css.
You could try something like this:
.myText
{
color: white; (or whatever)
opacity:0.5;
text-shadow:....
}
There is a massive amount of options for text shadow; but here is a generator you can play with.
I suppose you could also generate the two colours via javascript, should you wish to alter the colours depending on the image.
You shared no code so there is nothing I can improve upon so the best that can be done is to show you some shorthand CSS and minimal length CSS classes...
HTML
<span class="r">red</span>
CSS
.r {color: #f00;}