I am using xlsxwriter 1.1.0 and Microsoft Excel 2016 I copied the example listed here (my version pasted below):
######################################################################
#
# This program shows several examples of how to set up headers and
# footers with XlsxWriter.
#
# The control characters used in the header/footer strings are:
#
# Control Category Description
# ======= ======== ===========
# &L Justification Left
# &C Center
# &R Right
#
# &P Information Page number
# &N Total number of pages
# &D Date
# &T Time
# &F File name
# &A Worksheet name
#
# &fontsize Font Font size
# &"font,style" Font name and style
# &U Single underline
# &E Double underline
# &S Strikethrough
# &X Superscript
# &Y Subscript
#
# &[Picture] Images Image placeholder
# &G Same as &[Picture]
#
# && Miscellaneous Literal ampersand &
#
# See the main XlsxWriter documentation for more information.
#
# Copyright 2013-2018, John McNamara, jmcnamara#cpan.org
#
import xlsxwriter
workbook = xlsxwriter.Workbook('E:\\headers_footers.xlsx')
preview = 'Select Print Preview to see the header and footer'
######################################################################
#
# A simple example to start
#
worksheet1 = workbook.add_worksheet('Simple')
header1 = '&CHere is some centered text.'
footer1 = '&LHere is some left aligned text.'
worksheet1.set_header(header1)
worksheet1.set_footer(footer1)
worksheet1.set_column('A:A', 50)
worksheet1.write('A1', preview)
######################################################################
#
# Insert a header image.
#
worksheet2 = workbook.add_worksheet('Image')
header2 = '&L&G'
# Adjust the page top margin to allow space for the header image.
worksheet2.set_margins(top=1.3)
worksheet2.set_header(header2, {'image_left': 'logo.png'})
worksheet2.set_column('A:A', 50)
worksheet2.write('A1', preview)
######################################################################
#
# This is an example of some of the header/footer variables.
#
worksheet3 = workbook.add_worksheet('Variables')
header3 = '&LPage &P of &N' + '&CFilename: &F' + '&RSheetname: &A'
footer3 = '&LCurrent date: &D' + '&RCurrent time: &T'
worksheet3.set_header(header3)
worksheet3.set_footer(footer3)
worksheet3.set_column('A:A', 50)
worksheet3.write('A1', preview)
worksheet3.write('A21', 'Next sheet')
worksheet3.set_h_pagebreaks([20])
######################################################################
#
# This example shows how to use more than one font
#
worksheet4 = workbook.add_worksheet('Mixed fonts')
header4 = '&C&"Courier New,Bold"Hello &"Arial,Italic"World'
footer4 = '&C&"Symbol"e&"Arial" = mc&X2'
worksheet4.set_header(header4)
worksheet4.set_footer(footer4)
worksheet4.set_column('A:A', 50)
worksheet4.write('A1', preview)
######################################################################
#
# Example of line wrapping
#
worksheet5 = workbook.add_worksheet('Word wrap')
header5 = "&CHeading 1\nHeading 2"
worksheet5.set_header(header5)
worksheet5.set_column('A:A', 50)
worksheet5.write('A1', preview)
######################################################################
#
# Example of inserting a literal ampersand &
#
worksheet6 = workbook.add_worksheet('Ampersand')
header6 = '&CCuriouser && Curiouser - Attorneys at Law'
worksheet6.set_header(header6)
worksheet6.set_column('A:A', 50)
worksheet6.write('A1', preview)
workbook.close()
On line 40, I changed the destination of the file and on line 68 I changed the name of the image; I have changed nothing apart from that. When I run the said program I don't see the images as well as the fonts. I have attached a screenshot below:
The program finished correctly without throwing any exception. Most of the other functions like set_column, insert_image etc. are working. But set_header isn't.
I don't know if any more information is required. Please feel free to demand for the same if required.
Headers and Footers in Excel don't show up in the normal view of the worksheet. As the output from the example says "Select Print Preview to see the header and footer".
In Print Preview mode the output looks like this:
Or in "Page Layout" view it looks like this:
Related
I’m using this code to draw myself a server in visio:
import win32com.client as w32
visio = w32.Dispatch("visio.Application")
visio.Visible = 1
doc = visio.Documents.Add("Detailed Network Diagram.vst")
page = doc.Pages.Item(1)
page.name = "My drawing"
stn2 = visio.Documents("Servers.vss")
server = stn2.Masters("Server")
serv = page.Drop(server, 0, 0)
for ssh in serv.shapes:
ssh.Cells( 'Fillforegnd' ).FormulaForceU = 'RGB(255,0,0)'
And my problem is when I’m trying to fill the object with a color (instead of the regular server color) it doesn’t work.
Nothing really worked. I’m using python 3.8.
Try this code please
import win32com.client as w32
visio = w32.Dispatch("visio.Application")
visio.Visible = 1
doc = visio.activedocument
page = doc.pages(1)
page.name = "Mydrawing"
stn2 = visio.Documents(2)
server = stn2.Masters(2)
serv = page.Drop(server, 0, 0)
#iterate all sub-shapes into Serv-shape
for ssh in serv.shapes:
ssh.Cells( 'Fillforegnd' ).FormulaForceU = 'RGB(255,255,0)'
If you dont need iterate all sub-shapes, you can change only same of them
#iterate 2nd, 3rd and 4rd sub-shapes into Serv-shape #
for i in range (2,5):
ssh = serv.shapes(i)
# if you need get solid color for sub-shapes uncomment next line
# ssh.Cells('FillPattern').FormulaForceU = '1'
ssh.Cells('Fillforegnd').FormulaU = 'RGB(255,255,0)'
Code in my Jupyterlab notebook change only 3 sub-shapes, which i select and delete for demonstrate difference…
PS The user's problem was not in the code, but in the Visio sub-shapes, which did not want to inherit the color of the main shape. Because these sub-shapes had formulas that used functions like THEMEGUARD and similar to it in their cells.
I modified the shape from the built-in set of elements and the problem was solved…
PPS Solved! To remove the dependency on those sub-shapes, you need to change their Fillstyle to Normal. Just add new line of code ssh.FillStyle = 'Normal'.
Look at code ↓
import win32com.client as w32
visio = w32.Dispatch("visio.Application")
visio.Visible = 1
# create document based on Detailed Network Diagram template (use full path)
doc = visio.Documents.Add ("C:\Program Files\Microsoft Office\root\Office16\visio content\1033\dtlnet_m.vstx")
# use one of docked stencils
stn2 = visio.Documents("PERIPH_M.vssx")
# define 'Server' master-shape
server = stn2.Masters("Server")
# define page
page = doc.Pages.Item(1)
# rename page
page.name = "My drawing"
# drop master-shape on page, define 'Server' instance
serv = page.Drop(server, 0, 0)
# iterate sub-shapes (side edges)
for i in range (2,6):
# define one od side edges from 'Server'
ssh = serv.shapes(i)
# Change Fill Style to 'Normal'
ssh.FillStyle = 'Normal'
# fix FillForegnd cell for side edge
ssh.Cells( 'Fillforegnd' ).FormulaForceU = 'Guard(Sheet.' + str(serv.id) + '!FillForegnd)'
# fix FillBkgnd cell for side edge
ssh.Cells( 'FillBkgnd' ).FormulaForceU = 'Guard(Sheet.' + str(serv.id) + '!FillBkgnd)'
# instead formula 'Guard(x)' rewrite formula 'Guard(1)'
ssh.Cells( 'FillPattern' ).FormulaForceU = 'Guard(1)'
# fill main shape in 'Server' master-shape
serv.Cells("FillForegnd").FormulaForceU = '5'
I am trying to create a label with QR code and with some text and save the label as PDF. I am unable to alter the size of the label to 9 X 3 cms. How do I do that?
What I tried so far?
import requests
import shutil
zpl = """
^XA
^FO50,60^A0,15^FDID 123456^FS
^FO100,100
^BQN,2,5
^FDQA,QR_CODE^FS
^FO120,270^A0,15^FDTest here^FS
^FO150,290^A0,15^FDSome more text here^FS
^FO25,25^GB500,350,2^FS
^XZ
"""
# adjust print density (8dpmm), label width (4 inches), label height (6 inches), and label index (0) as necessary
url = 'http://api.labelary.com/v1/printers/8dpmm/labels/3.5x10/0/'
files = {'file' : zpl}
headers = {'Accept' : 'application/pdf'} # omit this line to get PNG images back
response = requests.post(url, headers = headers, files = files, stream = True)
if response.status_code == 200:
response.raw.decode_content = True
with open('label.pdf', 'wb') as out_file: # change file name for PNG images
shutil.copyfileobj(response.raw, out_file)
else:
print('Error: ' + response.text)
You need to find the right combination of basically 4 parameters, which are:
The size of your graphical elements in dots, for example the texts and the bounding box.
The density (or resolution) of your label, which should match your printer's.
The size of the (physical) label.
The size of the PDF page.
Here's an example of how to control each one of these.
Only the relevant lines are shown:
# The values in your ZPL set the sizes in dots:
zpl = """
^XA
^FO50,60^A0,15^FDID 123456^FS
... (your full ZPL here) ...
"""
# Then:
# 1. Set the density (24dpmm) and the size of the label in inches (2.8x2):
url = 'http://api.labelary.com/v1/printers/24dpmm/labels/2.8x2/0/'
# 2. Set the PDF page size, here A4:
headers = {'Accept' : 'application/pdf', 'X-Page-Size':'A4'}
Note: if the PDF page size is not set in the header, then it will match the physical label size.
I'm trying to make a simple report that has a header/footer and table in the middle with a ot of rows.
I'm new to ReportLab and the reason I switched from WeasyPrint is because I wanted the engine to handle page breaks nicely.
Below is my code :
def print_users(self):
buffer = self.buffer
doc = BaseDocTemplate(buffer,
rightMargin=20,
leftMargin=20,
topMargin=20,
bottomMargin=20,
pagesize=landscape(self.pagesize))
frame = Frame(
doc.leftMargin,
doc.bottomMargin,
doc.width,
doc.height - inch * 0.5,
id='normal',
showBoundary=1)
template = PageTemplate(id='all_pages', frames=frame, onPage=self._header_footer)
doc.addPageTemplates([template])
styles=getSampleStyleSheet()
# Our container for 'Flowable' objects
elements = []
elements.append(Spacer(1, 3*units.cm))
title = self.event.name
elements.append(Paragraph(self.event.name, styles["Normal"]))
elements.append(Spacer(1, 1*units.cm))
data = []
titles = ['First name', 'Last name', 'Position', 'Institution']
data.append(titles)
for invitation in self.invitations:
line = []
line.append(invitation.person.firstname)
line.append(invitation.person.lastname)
line.append(invitation.person.position)
line.append(invitation.institution.name)
data.append(line)
t=Table(data)
t.setStyle(TableStyle(
[('LINEBELOW',(0,0),(-1,-1),1, colors.gray)]))
table_story = [t]
elements.append(t)
# t_keep = KeepInFrame(0, 0, table_story, hAlign='CENTER', vAlign='MIDDLE', fakeWidth=False)
# write the document to disk
# Draw things on the PDF. Here's where the PDF generation happens.
# See the ReportLab documentation for the full list of functionality.
# elements.append(t_keep)
doc.build(elements)
The header/footer are showing fine and so is the table , but when we go to the second page, the table overrides the header.
I tried to add a frame with KeepInFrame ut the table becomes so small to fit inside the frame in one page.
It seems like a simple task, but i can't find a way to simply take into consideration the header on all pages. (Or maybe i'm taking the wrong approach?)
I face the same issue but in my case was because my header take like 20 mm of space meanwhile my topMargin was only 10mm. Changing the topMargin to more than 20 fix the issue.
I am trying to edit a QTextEdit named self.chatTextField to display the HTML preview in a live format. For example if I do "" I want it to not show the tag, but bold the text. I am able to have this work if I use textBrowswer as a previewer, but I would like it all to be in one widget.
As you can see in the image above, I want match the part the displays the HTML as final product and not the tags. Is this possible?
I have tried various ways to convert .toPlainText() and then adding an HTML header and footer. I have tried to .insertHtml() and .setHtml(). I have tried to do tricks with open and close carrots, but nothing seems to be working. I am either getting it to simply remove all HTML (anything with carrots/tags) or it is causing recursion errors.
This is the only section of code that is dealing with updating the HTML. If you need further code please let me know. I can provide UI file as well.
def printMaster(self):
global my_text
if self.chatTextField.toPlainText() != "":
oldText = self.chatTextField.toPlainText()
newText = self.textBrowser.toPlainText()
if oldText != newText and oldText != my_text:
self.textBrowser.setText(self.chatTextField.toPlainText())
my_text = self.chatTextField.toPlainText()
if my_text.endswith('>'):
#my_text = self.chatTextField.toHtml()
# self.chatTextField.clear()
print(my_text)
# self.chatTextField.setHtml(my_text)
QCoreApplication.processEvents()
# cursor = self.chatTextField.textCursor()
# pos = cursor.selectionEnd()
#
# print(self.chatTextField.toHtml())
#
# my_text = self.chatTextField.toHtml()
#
# self.chatTextField.clear()
# # self.chatTextField.insertHtml(str(my_text))
#
# if my_text.endswith('<'):
# my_text = my_text + "<"
# self.chatTextField.setHtml(my_text)
# print(True)
# else:
# self.chatTextField.insertHtml(my_text)
#
#
# cursor.setPosition(pos)
#
# self.chatTextField.setTextCursor(cursor)
#
#
# QCoreApplication.processEvents()
#
# # self.chatTextField.show()
I would like to change the font size of the title and of the body of my pptx-presentation. I tried to set it via title_shape.font = Pt(15) and body_shape.font = Pt(10), which does not work.
Here is my code:
from pptx import Presentation, util, text
from pptx.util import Cm, Pt
import fnmatch
import os
import contentOf_pptx as contOfPres
# ..............
# Generate presentation
# ..............
prs = Presentation()
#blank_slide_layout = prs.slide_layouts[6] #blank layout, see slide layout in powerpoint
title_only = prs.slide_layouts[5] #title only, see slide layout in powerpoint
# ..............
# set layout
# ..............
bullet_slide_layout = prs.slide_layouts[1]
slide = prs.slides.add_slide(bullet_slide_layout)
shapes = slide.shapes
title_shape = shapes.title
title_shape.font = Pt(15)
body_shape = shapes.placeholders[1]
body_shape.font = Pt(10)
# ..............
# set relevant text objects
# ..............
title_shape.text = 'Test Title'
tf = body_shape.text_frame
tf.text = 'Test SubText'
# ----------------------------------
# Store pptx
# ----------------------------------
prs.save('C:\\tests\\test_pptx_python.pptx')
A Shape object does not have a .font attribute (at least it didn't until you added one by assigning to that name :)
Font is characteristic of a Run object; a run is a sequence of characters that all share the same character formatting, also loosely known as a font.
A Paragraph object also has a .font property which is used the same way, but which specifies the default font for the runs in a paragraph. Individual runs in that paragraph can override that default by setting the attributes of their own font object.
If you only want one font for the shape (which is common), probably the fastest way is:
shape.text_frame.paragraphs[0].font.size = Pt(15)
which works because most shapes only contain a single paragraph (and all must contain at least one).
More thorough would be:
for paragraph in shape.text_frame.paragraphs:
paragraph.font.size = Pt(15)
and more thorough still would be:
for paragraph in shape.text_frame.paragraphs:
for run in paragraph.runs:
run.font.size = Pt(15)
More details on this are in the documentation here:
https://python-pptx.readthedocs.io/en/latest/user/text.html
Here is a simple approach that worked for me:
slide = prs.slides.add_slide(blank_slide_layout)
slide.shapes.title.text = "The Title of My Slide"
slide.shapes.title.text_frame.paragraphs[0].font.size = Pt(15)