im trying to define 2 images as header and a image as footer, but cant seem to resize it correctly.
docpath="/Users/ricardosimoes/Desktop/DESKTOP/Jira/my_word_file.docx"
mydoc = docx.Document()
section_h = mydoc.sections[0]
header = section_h.header
styles = mydoc.styles
style = styles.add_style('Tahoma',WD_STYLE_TYPE.PARAGRAPH)
style.font.name = 'Tahoma'
style.font.size = Pt(11)
shd = OxmlElement('w:background')
# Add attributes to the xml element
shd.set(qn('w:color'), '#0000FF')
shd.set(qn('w:themeColor'), 'text1')
shd.set(qn('w:themeTint'), 'F2')
# Add background element at the start of Document.xml using below
mydoc.element.insert(0, shd)
# Add displayBackgroundShape element to setting.xml
shd1 = OxmlElement('w:displayBackgroundShape')
mydoc.settings.element.insert(0, shd1)
paragraph_h = header.paragraphs[0]
runheader = paragraph_h.add_run()
runheader.add_picture("client_report/report_img/titulo.png", width=docx.shared.Inches(5), height=docx.shared.Inches(1))
paragraph_h = header.paragraphs[0]
runheader = paragraph_h.add_run()
runheader.add_picture("client_report/report_img/titulo_logo.png", width=docx.shared.Inches(5), height=docx.shared.Inches(1))
mydoc.add_picture("client_report/report_img/bottom.png", width=docx.shared.Inches(5),
height=docx.shared.Inches(1))
mydoc.save(docpath)
I need to specify that the titulo.png and bottom.png fit width of the page and the titulo_logo.png set in front of the titulo.png on the bottom corner left of the image.
Can this be done?
Related
I am using BalancedColumns to generate multiple column layout.
I am not sure, how to resolve an issue of the split happening of the Flowables across the column frames.
I have a heading and it's content. I don't want BalancedColumns to split the flowables in such a way that heading is part of one column and its content is part of another.
The content of the paragraph can split.
The basic python code:
from reportlab.platypus.flowables import BalancedColumns, CondPageBreak
from reportlab.platypus import BaseDocTemplate, Paragraph, Spacer, Frame, PageTemplate, PageBreak
from reportlab.lib.units import mm
from reportlab.lib.pagesizes import A4, LETTER
import os
from reportlab.lib.colors import HexColor
framewidth = A4[0] - 10*mm
frameheight = A4[1] - 20*mm
portrait_frame = Frame(5*mm, 10*mm, framewidth, frameheight,
leftPadding=0,
bottomPadding=0,
rightPadding=0,
topPadding=0,
id=0,
showBoundary=False )
pTemplate = PageTemplate(id=0,frames=[portrait_frame])
templates = [pTemplate]
pdfPath = os.path.abspath(os.path.join(os.path.dirname(__file__), 'balancedColTest.pdf'))
doc = BaseDocTemplate(pdfPath, pagesize=A4, rightMargin=2*mm, leftMargin=2*mm,topMargin=5*mm,bottomMargin=5*mm,showBoundary=0)
doc.addPageTemplates(templates)
# generate stories for balanced columns
story = []
minPadding = 2
for i in range(3):
fs = []
numOfFlowables = random.choice([2, 5, 6, 1, 3])
padding = minPadding + 5*i
for ii in range(numOfFlowables):
text = '<b> <font color="#77D179"> Heading </font></b> <br/>'
heading = Paragraph(text)
heading.keepWithNext = True
fs.append(heading)
fs.append(Paragraph("This is another text in new Para flowable."))
# numCols = 2 if i%2 == 0 else 3
numCols = 2
bCols = BalancedColumns(fs, nCols=numCols, spaceAfter=5*mm, vLinesStrokeColor=HexColor('#77D179'), vLinesStrokeWidth=0.5)
story.append(bCols)
doc.build(story)
Even if I try to use keepWithNext=True the flowables are not part of same frame.
If I use KeepTogether, the BalanceColumns takes the entire space of the page.
heading = Paragraph(text)
content = Paragraph("This is another text in the paragraph")
f= KeepTogether([heading, content])
fs.append(f)
Can anyone suggest a solution so that the heading and its underlying paragraph can remain in the same frame?
Need some help.
I'm writing the code to get file name from List and use those file name to look in folder for get the images place on PowerPoint slide. The purpose is I would like to add three image on same slide. So, every slide will have 3 images and so on...
Let say...
Slide1 : place image file name aaaa-1.jpg, aaaa-2.jpg, aaaa-3.jpg
Slide2 : Place image file name bbbb-1.jpg, bbbb-2.jpg, bbbb-3.jpg
... and so on until end of data in list
The file name that keep in list look like this ..list =['aaaa-1.jpg', 'aaaa-2.jpg', 'aaaa-3.jpg', 'bbb-1.jpg, bbbb-2.jpg', 'bbbb-3.jpg' ...]
I use function to send files name to pptx creating module but it doesn't work. After run this code, they build 3 images (with same file) in one slide!
Could you kindly please advise.
Thanks for all answers from your guy.
Here is my code
from pptx import Presentation
from pptx.util import Inches
import os
prs = Presentation()
prs.slide_height=Inches(9)
prs.slide_width=Inches(16)
def buildafm(f1,f2,f3): #pass f1, f2, f3 to function
blank_slide_layout = prs.slide_layouts[6]
slide = prs.slides.add_slide(blank_slide_layout)
os.chdir(r"C:\Python38-32\faprojects\folders\hzt")
left = top = Inches(1)
height = Inches(3.5)
width = Inches(3.5)
pic = slide.shapes.add_picture(f1, left, top, width=width, height=height)
left = Inches(5)
top = Inches(1)
height = Inches(3.5)
width = Inches(3.5)
pic = slide.shapes.add_picture(f2, left, top, width=width, height=height)
left = Inches(9)
top = Inches(1)
height = Inches(3.5)
width = Inches(5.5)
pic = slide.shapes.add_picture(f3, left, top, width=width, height=height)
os.chdir(r"C:\Python38-32\faprojects\folders\hzt")
a = os.listdir(os.getcwd())
# Image files name in folder HZT
#a=['aaaaaaaaaaa.001.jpg','aaaaaaaaaaaa.002.jpg','bbbbbbbbbb.001.jpg','bbbbbbbbbb.002.jpg','cccccccccc.001.jpg','cccccccccc.002.jpg']
newList = [string[:10] for string in a]
print("here is new list",newList)
no_dupes = [x for n, x in enumerate(newList) if x not in newList[:n]]
print("here is new list",no_dupes)
print("Number of heads",len(no_dupes))
hd=no_dupes[0:1]
str1=""
hd=str1.join(hd)
print(hd)
res = list(filter(lambda x: hd in x, a))
print("file is",res)
'''f1 = res[0:1]
f2 = res[1:2]
f3 = res[2:3]'''
for t in res:
print(t)
#showdata(t)
buildafm(t,t,t) #call function to create pptx
prs.save('testbat.pptx')
os.startfile("testbat.pptx")
I am trying to make contour plot from unstructured grid. My code does not work and I could not find an example to follow. I did not include the input file, hoping that a sample unstructured grid is easy to find. I managed to make work on Paraview by converting cell data to point data and then contouring "p" scalar. But I cannot do it with vtk. What's wrong in my code?
from vtk import *
file_name = "results.vtk"
reader = vtkUnstructuredGridReader()
reader.SetFileName(file_name)
reader.Update()
output = reader.GetOutput()
scalar_range = output.GetScalarRange()
c2p = vtkCellDataToPointData()
c2p.SetInputData(output)
contours = vtkContourGrid()
contours.SetInputData(c2p.GetOutput())
contours.SetValue(0, 0.007009505294263363)
gridmapper = vtkDataSetMapper()
gridmapper.SetInputData(output)
gridmapper.GetInput().GetCellData().SetActiveScalars("p")
gridmapper.SetScalarVisibility(1)
gridmapper.SetScalarRange(scalar_range)
mapper = vtkPolyDataMapper()
#mapper = vtkDataSetMapper()
mapper.SetInputConnection(contours.GetOutputPort())
actor = vtkActor()
actor.SetMapper(mapper)
gridactor = vtkActor()
gridactor.SetMapper(gridmapper)
gridactor.GetProperty().EdgeVisibilityOn()
renderer = vtkRenderer()
renderer.AddActor(actor)
renderer.AddActor(gridactor)
#renderer.SetBackground(1, 1, 1) # Set background to white
renderer_window = vtkRenderWindow()
renderer_window.AddRenderer(renderer)
interactor = vtkRenderWindowInteractor()
interactor.SetRenderWindow(renderer_window)
interactor.Initialize()
interactor.Start()
How do you turn off (or hide) the seconds y axis scale on a combination chart in openpyxl?
I can find the xml difference by comparing the before and after changes to hide the scale (I just change the excel file extension to '.zip' to access the xml):
-<c:valAx>
<c:axId val="156672520"/>
-<c:scaling>
<c:orientation val="minMax"/>
</c:scaling>
<c:delete val="0"/>
<c:axPos val="r"/>
<c:majorGridlines/>
<c:numFmt sourceLinked="1" formatCode="0.0"/>
<c:majorTickMark val="out"/>
<c:minorTickMark val="none"/>
<c:tickLblPos val="none"/> # this changes from 'nextTo'
<c:crossAx val="207247000"/>
<c:crosses val="max"/>
<c:crossBetween val="between"/>
</c:valAx>
I've tried this (last few lines are the 'tickLblPos' ):
mainchart = LineChart()
mainchart.style = 12
v2 = Reference(WorkSheetOne, min_col=1, min_row=2+CombBarLineDataOffsetFromTop, max_row=3+CombBarLineDataOffsetFromTop, max_col=13)
mainchart.add_data(v2, titles_from_data=True, from_rows=True)
mainchart.layout = Layout(
ManualLayout(
x=0.12, y=0.25, # position from the top
h=0.9, w=0.75, # this is scaling the chart into the container
xMode="edge",
yMode="edge",
)
)
mainchart.title = "Chart Title"
# Style the lines
s1 = mainchart.series[0]
#Marker type
s1.marker.symbol = "diamond" # triangle
s1.marker.size = 9
s1.marker.graphicalProperties.solidFill = "C00000" # Marker filling
s1.marker.graphicalProperties.line.solidFill = "000000" # Marker outline
s1.graphicalProperties.line.noFill = False
# Line color
s1.graphicalProperties.line.solidFill = "000000" # line color
s2 = mainchart.series[1]
s2.graphicalProperties.line.solidFill = "000000"
s2.graphicalProperties.line.dashStyle = "dash"
mainchart.dataLabels = DataLabelList()
mainchart.dataLabels.showVal = False
mainchart.dataLabels.dLblPos = 't'
mainchart.height = 15
mainchart.width = 39
#Create the Chart
chart2 = BarChart()
chart2.type = "col"
chart2.style = 10 # simple bar
chart2.y_axis.axId = 0
dataone = Reference(WorkSheetOne, min_col=2, min_row=CombBarLineDataOffsetFromTop+1, max_row=CombBarLineDataOffsetFromTop+1, max_col=13 )
doneseries = Series(dataone, title="Series Title")
chart2.append(doneseries)
cats = Reference(WorkSheetOne, min_col=2, min_row=CombBarLineDataOffsetFromTop, max_row=CombBarLineDataOffsetFromTop, max_col=13)
chart2.set_categories(cats)
# Set the series for the chart data
series3Total = chart2.series[0]
fill3Total = PatternFillProperties(prst="pct5")
fill3Total.foreground = ColorChoice(srgbClr='996633') # brown
fill3Total.background = ColorChoice(srgbClr='996633')
series3Total.graphicalProperties.pattFill = fill3Total
chart2.dataLabels = DataLabelList()
chart2.dataLabels.showVal = False
chart2.shape = 2
mainchart.y_axis.crosses = "max"
mainchart.y_axis.tickLblPos = "none" # nextTo -- this doesn't work
mainchart += chart2
WorkSheetOne.add_chart(mainchart, 'A1')
How can I translate the difference in the XML to an attribute with openpyxl?
The problem here is with some of default values for some attributes which use 3-valued logic at times so that None != "none", ie. <c:tickLblPos /> != <c:tickLblPos val="none"/> because the default is "nextTo". This plays havoc with the Python semantics (3-valued logic is always wrong) where the default is not to set an attribute if the value is None in Python. This really only affects ChartML and I've added some logic to the descriptors for the relevant objects so that "none" will be written where required.
But this code isn't publicly available yet. Get in touch with my by e-mail if you'd like a preview.
I'm using a script I found online to convert some files through parsing some XML. The script was built in Python 2.6 and it's using a module that I believe doesn't come with 2.6 through what I've read on the web. I'm wondering if there's a work around. The error I am getting is:
No Module name EXT
In the following script, I think it's getting hung up on import xml.dom.ext and it only seems to use this object at the very end to PrettyPrint (See the very last Try statement) I'm wondering if there's a workaround for this in 2.6? I can't seem to find a module that contains the EXT object which I can import.
The script is:
from xml.dom.minidom import Document
import xml.dom.ext
import string
import os
import arcpy
#Read input parameters from GP dialog
output = arcpy.GetParameterAsText(0)
#Create an output qgs file
f = open(output, "w")
# Create the minidom
doc = Document()
# Create the <qgis> base element
qgis = doc.createElement("qgis")
qgis.setAttribute("projectname", " ")
qgis.setAttribute("version", "1.6.0-Capiapo")
doc.appendChild(qgis)
# Create the <title> element
title = doc.createElement("title")
qgis.appendChild(title)
# Assign current document
mxd = arcpy.mapping.MapDocument("CURRENT")
print 'Converting mxd........'
# Dataframe elements
df = arcpy.mapping.ListDataFrames(mxd)[0]
unit = doc.createTextNode(df.mapUnits)
xmin1 = doc.createTextNode(str(df.extent.XMin))
ymin1 = doc.createTextNode(str(df.extent.YMin))
xmax1 = doc.createTextNode(str(df.extent.XMax))
ymax1 = doc.createTextNode(str(df.extent.YMax))
# srsid = doc.createTextNode
srid1 = doc.createTextNode(str(df.spatialReference.factoryCode))
srid2 = doc.createTextNode(str(df.spatialReference.factoryCode))
epsg1 = doc.createTextNode(str(df.spatialReference.factoryCode))
epsg2 = doc.createTextNode(str(df.spatialReference.factoryCode))
description1 = doc.createTextNode(str(df.spatialReference.name))
description2 = doc.createTextNode(str(df.spatialReference.name))
ellipsoidacronym1 = doc.createTextNode(str(df.spatialReference.name))
ellipsoidacronym2 = doc.createTextNode(str(df.spatialReference.name))
geographicflag1 = doc.createTextNode("true")
geographicflag2 = doc.createTextNode("true")
authid2 = doc.createTextNode("EPSG:"+str(df.spatialReference.factoryCode))
authid3 = doc.createTextNode("EPSG:"+str(df.spatialReference.factoryCode))
# Layerlist elements
lyrlist = arcpy.mapping.ListLayers(df)
count1 = str(len(lyrlist))
# mapcanvas
def map_canvas():
# Create the <mapcanvas> element
mapcanvas = doc.createElement("mapcanvas")
qgis.appendChild(mapcanvas)
# Create the <units> element
units = doc.createElement("units")
units.appendChild(unit)
mapcanvas.appendChild(units)
# Create the <extent> element
extent = doc.createElement("extent")
mapcanvas.appendChild(extent)
# Create the <xmin> element
xmin = doc.createElement("xmin")
xmin.appendChild(xmin1)
extent.appendChild(xmin)
# Create the <ymin> element
ymin = doc.createElement("ymin")
ymin.appendChild(ymin1)
extent.appendChild(ymin)
# Create the <xmax> element
xmax = doc.createElement("xmax")
xmax.appendChild(xmax1)
extent.appendChild(xmax)
# Create the <ymax> element
ymax = doc.createElement("ymax")
ymax.appendChild(ymax1)
extent.appendChild(ymax)
# Create the <projections> element
projections = doc.createElement("projections")
mapcanvas.appendChild(projections)
# Create the <destinationsrs> element
destinationsrs = doc.createElement("destinationsrs")
mapcanvas.appendChild(destinationsrs)
# Create the <spatialrefsys> element
spatialrefsys = doc.createElement("spatialrefsys")
destinationsrs.appendChild(spatialrefsys)
# Create the <proj4> element
proj4 = doc.createElement("proj4")
spatialrefsys.appendChild(proj4)
# Create the <srsid> element
srsid = doc.createElement("srsid")
spatialrefsys.appendChild(srsid)
# Create the <srid> element
srid = doc.createElement("srid")
srid.appendChild(srid1)
spatialrefsys.appendChild(srid)
# Create the <authid> element
authid = doc.createElement("authid")
authid.appendChild(authid2)
spatialrefsys.appendChild(authid)
# Create the <description> element
description = doc.createElement("description")
description.appendChild(description1)
spatialrefsys.appendChild(description)
# Create the <projectionacronym> element
projectionacronym = doc.createElement("projectionacronym")
spatialrefsys.appendChild(projectionacronym)
# Create the <ellipsoidacronym element
ellipsoidacronym = doc.createElement("ellipsoidacronym")
ellipsoidacronym.appendChild(ellipsoidacronym1)
spatialrefsys.appendChild(ellipsoidacronym)
# Create the <geographicflag> element
geographicflag = doc.createElement("geographicflag")
geographicflag.appendChild(geographicflag1)
spatialrefsys.appendChild(geographicflag)
# Legend
def legend_func():
# Create the <legend> element
legend = doc.createElement("legend")
qgis.appendChild(legend)
for lyr in lyrlist:
if(lyr.isGroupLayer == False):
# Create the <legendlayer> element
legendlayer = doc.createElement("legendlayer")
legendlayer.setAttribute("open", "true")
legendlayer.setAttribute("checked", "Qt::Checked")
legendlayer.setAttribute("name",str(lyr.name))
legend.appendChild(legendlayer)
# Create the <filegroup> element
filegroup = doc.createElement("filegroup")
filegroup.setAttribute("open", "true")
filegroup.setAttribute("hidden", "false")
legendlayer.appendChild(filegroup)
# Create the <legendlayerfile> element
legendlayerfile = doc.createElement("legendlayerfile")
legendlayerfile.setAttribute("isInOverview", "0")
legendlayerfile.setAttribute("layerid", str(lyr.name)+str(20110427170816078))
legendlayerfile.setAttribute("visible", "1")
filegroup.appendChild(legendlayerfile)
# Project Layers
def project_layers():
# Create the <projectlayers> element
projectlayers = doc.createElement("projectlayers")
projectlayers.setAttribute("layercount", count1)
qgis.appendChild(projectlayers)
for lyr in lyrlist:
if(lyr.isGroupLayer == False and lyr.isRasterLayer == False):
geometry1 = arcpy.Describe(lyr)
geometry2 = str(geometry1.shapeType)
ds = doc.createTextNode(str(lyr.dataSource))
name1 = doc.createTextNode(str(lyr.name)+str(20110427170816078))
name2 = doc.createTextNode(str(lyr.name))
# Create the <maplayer> element
maplayer = doc.createElement("maplayer")
maplayer.setAttribute("minimumScale", "0")
maplayer.setAttribute("maximumScale", "1e+08")
maplayer.setAttribute("minLabelScale", "0")
maplayer.setAttribute("maxLabelScale", "1e+08")
maplayer.setAttribute("geometry", geometry2)
if(lyr.isRasterLayer == True):
maplayer.setAttribute("type", "raster")
else:
maplayer.setAttribute("type", "vector")
maplayer.setAttribute("hasScaleBasedVisibilityFlag", "0")
maplayer.setAttribute("scaleBasedLabelVisibilityFlag", "0")
projectlayers.appendChild(maplayer)
# Create the <id> element
id = doc.createElement("id")
id.appendChild(name1)
maplayer.appendChild(id)
# Create the <datasource> element
datasource = doc.createElement("datasource")
datasource.appendChild(ds)
maplayer.appendChild(datasource)
# Create the <layername> element
layername = doc.createElement("layername")
layername.appendChild(name2)
maplayer.appendChild(layername)
# Create the <srs> element
srs = doc.createElement("srs")
maplayer.appendChild(srs)
# Create the <spatialrefsys> element
spatialrefsys = doc.createElement("spatialrefsys")
srs.appendChild(spatialrefsys)
# Create the <proj4> element
proj4 = doc.createElement("proj4")
spatialrefsys.appendChild(proj4)
# Create the <srsid> element
srsid = doc.createElement("srsid")
spatialrefsys.appendChild(srsid)
# Create the <srid> element
srid = doc.createElement("srid")
srid.appendChild(srid2)
spatialrefsys.appendChild(srid)
# Create the <authid> element
authid = doc.createElement("authid")
authid.appendChild(authid3)
spatialrefsys.appendChild(authid)
# Create the <description> element
description = doc.createElement("description")
description.appendChild(description2)
spatialrefsys.appendChild(description)
# Create the <projectionacronym> element
projectionacronym = doc.createElement("projectionacronym")
spatialrefsys.appendChild(projectionacronym)
# Create the <ellipsoidacronym element
ellipsoidacronym = doc.createElement("ellipsoidacronym")
ellipsoidacronym.appendChild(ellipsoidacronym2)
spatialrefsys.appendChild(ellipsoidacronym)
# Create the <geographicflag> element
geographicflag = doc.createElement("geographicflag")
geographicflag.appendChild(geographicflag2)
spatialrefsys.appendChild(geographicflag)
# Create the <transparencyLevelInt> element
transparencyLevelInt = doc.createElement("transparencyLevelInt")
transparency2 = doc.createTextNode("255")
transparencyLevelInt.appendChild(transparency2)
maplayer.appendChild(transparencyLevelInt)
# Create the <customproperties> element
customproperties = doc.createElement("customproperties")
maplayer.appendChild(customproperties)
# Create the <provider> element
provider = doc.createElement("provider")
provider.setAttribute("encoding", "System")
ogr = doc.createTextNode("ogr")
provider.appendChild(ogr)
maplayer.appendChild(provider)
# Create the <singlesymbol> element
singlesymbol = doc.createElement("singlesymbol")
maplayer.appendChild(singlesymbol)
# Create the <symbol> element
symbol = doc.createElement("symbol")
singlesymbol.appendChild(symbol)
# Create the <lowervalue> element
lowervalue = doc.createElement("lowervalue")
symbol.appendChild(lowervalue)
# Create the <uppervalue> element
uppervalue = doc.createElement("uppervalue")
symbol.appendChild(uppervalue)
# Create the <label> element
label = doc.createElement("label")
symbol.appendChild(label)
# Create the <rotationclassificationfieldname> element
rotationclassificationfieldname = doc.createElement("rotationclassificationfieldname")
symbol.appendChild(rotationclassificationfieldname)
# Create the <scaleclassificationfieldname> element
scaleclassificationfieldname = doc.createElement("scaleclassificationfieldname")
symbol.appendChild(scaleclassificationfieldname)
# Create the <symbolfieldname> element
symbolfieldname = doc.createElement("symbolfieldname")
symbol.appendChild(symbolfieldname)
# Create the <outlinecolor> element
outlinecolor = doc.createElement("outlinecolor")
outlinecolor.setAttribute("red", "88")
outlinecolor.setAttribute("blue", "99")
outlinecolor.setAttribute("green", "37")
symbol.appendChild(outlinecolor)
# Create the <outlinestyle> element
outlinestyle = doc.createElement("outlinestyle")
outline = doc.createTextNode("SolidLine")
outlinestyle.appendChild(outline)
symbol.appendChild(outlinestyle)
# Create the <outlinewidth> element
outlinewidth = doc.createElement("outlinewidth")
width = doc.createTextNode("0.26")
outlinewidth.appendChild(width)
symbol.appendChild(outlinewidth)
# Create the <fillcolor> element
fillcolor = doc.createElement("fillcolor")
fillcolor.setAttribute("red", "90")
fillcolor.setAttribute("blue", "210")
fillcolor.setAttribute("green", "229")
symbol.appendChild(fillcolor)
# Create the <fillpattern> element
fillpattern = doc.createElement("fillpattern")
fill = doc.createTextNode("SolidPattern")
fillpattern.appendChild(fill)
symbol.appendChild(fillpattern)
# Create the <texturepath> element
texturepath = doc.createElement("texturepath")
texturepath.setAttribute("null", "1")
symbol.appendChild(texturepath)
map_canvas()
legend_func()
project_layers()
# Write to qgis file
try:
xml.dom.ext.PrettyPrint(doc, f)
finally:
f.close()
print 'Done'
The xml.dom.ext module was never added to the Python standard library.
It was only ever part of the PyXML distribution, but that has not seen any updates in years and I doubt it'll still work on Python 2.6.
Instead, just call the minidom .toprettyxml() method on your document to pretty print the output, then write that data out to the file:
f.write(doc.toprettyxml())