Replace picture (from page header) - python-docx

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')

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);

Read HTML code from file system and show in TYPO3 page

Setup
I want to transfer data from my project to a TYPO3 instance. Assume I have an HTML export that generates about 20 different HTML files inside my TYPO3 directory. These files contain data from a different system and the data updates quite frequently, so I am overwriting them regularly with the newest information.
Problem
I would like to tell TYPO3 to load the HTML contents of each file as its own page. Please note: the pages are not complete html documents (no <html> or <body> tags). Instead, I want whatever code is in those files to be displayed inside the context of a TYPO3 page. Kind of like a TYPO3 HTML PageContent, but I want the source for the HTML to be from a file.
I don't care if I have to manually set up each page, but I haven't found any way to let a TYPO3 Page or PageContent get its data from a file. Do you know of any way this would be possible?
Note: iframe isn't a solution in my case. I am using TYPO3 7.6.23
My answer is based on the following assumptions:
You have you have a "frontend provider extension" EXT:yourext; if not you can change every path like EXT:yourext/Resources/Private/Etcetera with the proper ´fileadmin/etcetera/Resources/Private/Etcetera´
You use backend_layout on database to store the backend layout and use that field to control the frontend template. I don't remember if in version 7 you can also use the filesystem using key.data=pagelayout
of course you have to adjust the IDs of the backend_layout items
the files to include will be partials, stored in the folder EXT:yorext/Resources/Private/Partials/ and will be named
MyFileToIncludeOne.html
MyFileToIncludeTwo.html
et cetera
The basic TypoScript will be something like:
page.10 = FLUIDTEMPLATE
page.10{
templateName= TEXT
templateName.stdWrap {
cObject = CASE
cObject {
key.data = levelfield:-2,backend_layout_next_level,slide
key.override.field = backend_layout
//I assume you already have some templates
1 = TEXT
1.value = Default
2 = TEXT
2.value = Home
//The layouts for the "pages with html files" begin here
10 = TEXT
10.value = MyFileOne
11 =TEXT
11.value = MyFileTwo
}
}
layoutRootPaths {
0 = EXT:yourext/Resouces/Private/Layouts/Page/
}
partialRootPaths {
0 = EXT:yourext/Resouces/Private/Partials/Page/
}
templateRootPaths {
0 = EXT:yourext/Resouces/Private/Template/Page/
}
}
So, in the previous lines,
the template MyFileOne.html will include the partial MyFileToIncludeOne.html, with just writing in it:
<f:render partial="MyFileToIncludeOne"/>
You could also use distinct paths if you want to keep the files separated:
partialRootPaths {
0 = EXT:yourext/Resouces/Private/Partials/Page/
1 = fileadmin/some/other/path/
}
I hope I have not forgotten important passages. Feel free to ask for clarifications

pdfHTML with in-memory CSS

I'm trying out iText7 and trying to piece together how to do things. It seems that I can put in a base URI to grab external resources which I'm assuming if it finds a .css it will apply that? I have a particular situation where it's easier for me to hold the CSS in memory as a string. It seems odd that I can use HtmlConverter.convertToPdf() and pass in HTML as a string but not CSS.
As a secondary question, what happens if it finds multiple CSS files at that base URI?
Finally (sorry for the dump), if the HTML contains FQDN URLs to images, I'm assuming/hoping it will pull the images directly? In other words, I'm hoping I don't also have to store/write those images to the specified base URI?
Thanks.
UPDATE: I put together a quick demo. I found out it will download images that have a full URL which is great.
However, it does not seem to be loading the CSS file that is in a folder I specified. The code:
StringBuilder sb = new StringBuilder(File.ReadAllText("demoHtml.html"));
// this folder, which is relative to the test .exe, contains a file called pdf.css
ConverterProperties props = new ConverterProperties().SetBaseUri("Content/Pdf");
FileStream fs = new FileStream("itext.pdf", FileMode.Create);
HtmlConverter.ConvertToPdf(sb.ToString(), fs, props);
And the CSS:
img {
max-width: 100%;
}
table {
vertical-align: top;
}
td ol {
-webkit-padding-start: 15px;
padding-left: 15px;
}
thead tr {
background: #aaa;
}
tr:nth-child(even) {
background: #eee;
}
Solution to question 1:
I'm trying out iText7 and trying to piece together how to do things. It seems that I can put in a base URI to grab external resources which I'm assuming if it finds a .css it will apply that? I have a particular situation where it's easier for me to hold the CSS in memory as a string. It seems odd that I can use HtmlConverter.convertToPdf() and pass in HTML as a string but not CSS.
Many hours i have spent finding the slution for this problem. Everything seemed right and i even asked a support question about the using of CSS files. In contrary to itext5 (itextsharp), itext7 can't manage an url with a space in it.
So locally testing in a path like this: c:/Path to project/project/name/wwwroot/ won't work (note the spaces)
I didn't notice this at first because i generated my path programmatically to my css folder:
var basepath = env.ContentRootPath + "\\wwwroot\\pdfcss\\";
Changed it to:
var basepath = #"G:\some-other\directory\pdfcss\";
Solution to question 2:
Now knowing this i could solve your second question:
As a secondary question, what happens if it finds multiple CSS files at that base URI?
Nothing, you will still have to insert the links into your html in the head element. If this isn't added you will not have any css!
Solution to question 3:
And indeed:
Finally (sorry for the dump), if the HTML contains FQDN URLs to images, I'm assuming/hoping it will pull the images directly? In other words, I'm hoping I don't also have to store/write those images to the specified base URI?
You can do the following:
<img id="logo"
src="https://xxxxx.blob.core.windows.net/path/to-image-
logo.png" />

How to render HTML Django page to PDF?

I have a task to render an HTML page with dynamic data and turn it into PDF, but, I have a problem achieving it.
def makepdf(request):
if request.POST:
chatvs = Competirors.objects.get(id = int(request.POST.get('competitor', '')))
jivo_staff = Manager.objects.get(id = int(request.POST.get('manager', '')))
business = Field.objects.get(id = int(request.POST.get('filed', '')))
business = business.link.all().order_by('?')[0:3]
context = {
"chatvs" : chatvs,
"jivo_staff" : jivo_staff,
"business" : business,
}
tmpl = get_template('marketing/jivopdf.html', )
html = tmpl.render(context)
# and i have a problem there with pdfkit
I was using Pdfcrowd API, but it cuts all CSS styles and does not look nice. As for vvwkhtmltopdf/pdfkit - I don't know how to make it a rendered HTML page, as it accesses only the url/file/string.
Is there a way to render ready HTML page?
Hard to say without knowing the error you get.
But what I can see from your code, if this is your real code. Looks like a spelling mistake in Competirors.objects.get, should probably be named Competitors.
And if you get the POST data from a form, you shouldn't use it directly.
Never trust user input...
I suggest you try weasyprint .

Styling text inside a property files

I'm using properties files in my webapp to cater i18n needs. Sometimes the text that I'm translating needs to have individual styling. For example:
options.reduce.co2.label = To reduce your CO2 emission, click here!
Should actually be rendered as:
To reduce your CO<span class="subscript">2</span> emission, click here!
The diry fix would be to include this styling in my properties file. However, I really want to avoid this!
A more clean approach would be to split up all the parts of the text:
options.reduce.co2.label.part1 = To reduce your CO
options.reduce.co2.label.part2 = 2
options.reduce.co2.label.part3 = emission,
options.reduce.co2.label.part4 = click here
options.reduce.co2.label.part5 = !
However, this makes the property files a big mess of words rather than structured sentences.
How do you generally deal with this situation? I want to achieve maximum readability and maintainability for the developers.
I always use placeholders for this kind of stuff:
options.reduce.co2.label = To reduce your CO%s2%s emission, click %shere%s!