How to convert a Python string into its escaped version in C++? - python

I'm trying to write a Python program that reads in a file and prints the contents as a single string as it would be escaped in a C++ format. This is because the string will be copied from Python output and pasted into a C++ program (C++ string variable definition).
Basically, I want to convert
<!DOCTYPE html>
<html>
<style>
.card{
max-width: 400px;
min-height: 250px;
background: #02b875;
padding: 30px;
box-sizing: border-box;
color: #FFF;
margin:20px;
box-shadow: 0px 2px 18px -4px rgba(0,0,0,0.75);
}
</style>
<body>
<div class="card">
<h4>The ESP32 Update web page without refresh</h4><br>
<h1>Sensor Value:<span id="ADCValue">0</span></h1><br>
</div>
</body>
<script>
setInterval(function() {
// Call a function repetatively with 0.1 Second interval
getData();
}, 100); //100mSeconds update rate
function getData() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("ADCValue").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "readADC", true);
xhttp.send();
}
</script>
</html>
to this
<!DOCTYPE html>\n<html>\n<style>\n.card{\n max-width: 400px;\n min-height: 250px;\n background: #02b875;\n padding: 30px;\n box-sizing: border-box;\n color: #FFF;\n margin:20px;\n box-shadow: 0px 2px 18px -4px rgba(0,0,0,0.75);\n}\n</style>\n\n<body>\n<div class=\"card\">\n <h4>The ESP32 Update web page without refresh</h4><br>\n <h1>Sensor Value:<span id=\"ADCValue\">0</span></h1><br>\n</div>\n</body>\n\n<script>\nsetInterval(function() {\n // Call a function repetatively with 0.1 Second interval\n getData();\n}, 100); //100mSeconds update rate\n\nfunction getData() {\n var xhttp = new XMLHttpRequest();\n xhttp.onreadystatechange = function() {\n if (this.readyState == 4 && this.status == 200) {\n document.getElementById(\"ADCValue\").innerHTML =\n this.responseText;\n }\n };\n xhttp.open(\"GET\", \"readADC\", true);\n xhttp.send();\n}\n</script>\n</html>
Using this Python program:
if __name__ == '__main__':
with open(<filepath>) as html:
contents = html.read().replace('"', r'\"')
print(contents)
print('')
print(repr(contents))
I get exactly what I want minus double backslashes when "escaping" the double quotes. I've tried a few random things, but all the attempts either get rid of both backslashes or don't change the string at all.
I simply want to add a single backslash before all the double quotes in my string. Is this even possible in Python?

You can use str.translate to map the troublesome characters to their escaped equivalents. Since python's rules on escape and quote characters can be a bit baroque, I've just brute forced them for consistency.
# escapes for C literal strings
_c_str_trans = str.maketrans({"\n": "\\n", "\"":"\\\"", "\\":"\\\\"})
if __name__ == '__main__':
with open(<filepath>) as html:
contents = html.read().translate(_c_str_trans)
print(contents)
print('')
print(repr(contents))

Related

how to I download csv file from github [duplicate]

Lets say there's a file that lives at the github repo:
https://github.com/someguy/brilliant/blob/master/somefile.txt
I'm trying to use requests to request this file, write the content of it to disk in the current working directory where it can be used later. Right now, I'm using the following code:
import requests
from os import getcwd
url = "https://github.com/someguy/brilliant/blob/master/somefile.txt"
directory = getcwd()
filename = directory + 'somefile.txt'
r = requests.get(url)
f = open(filename,'w')
f.write(r.content)
Undoubtedly ugly, and more importantly, not working. Instead of the expected text, I get:
<!DOCTYPE html>
<!--
Hello future GitHubber! I bet you're here to remove those nasty inline styles,
DRY up these templates and make 'em nice and re-usable, right?
Please, don't. https://github.com/styleguide/templates/2.0
-->
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>Page not found · GitHub</title>
<style type="text/css" media="screen">
body {
background: #f1f1f1;
font-family: "HelveticaNeue", Helvetica, Arial, sans-serif;
text-rendering: optimizeLegibility;
margin: 0; }
.container { margin: 50px auto 40px auto; width: 600px; text-align: center; }
a { color: #4183c4; text-decoration: none; }
a:visited { color: #4183c4 }
a:hover { text-decoration: none; }
h1 { letter-spacing: -1px; line-height: 60px; font-size: 60px; font-weight: 100; margin: 0px; text-shadow: 0 1px 0 #fff; }
p { color: rgba(0, 0, 0, 0.5); margin: 20px 0 40px; }
ul { list-style: none; margin: 25px 0; padding: 0; }
li { display: table-cell; font-weight: bold; width: 1%; }
#error-suggestions { font-size: 14px; }
#next-steps { margin: 25px 0 50px 0;}
#next-steps li { display: block; width: 100%; text-align: center; padding: 5px 0; font-weight: normal; color: rgba(0, 0, 0, 0.5); }
#next-steps a { font-weight: bold; }
.divider { border-top: 1px solid #d5d5d5; border-bottom: 1px solid #fafafa;}
#parallax_wrapper {
position: relative;
z-index: 0;
}
#parallax_field {
overflow: hidden;
position: absolute;
left: 0;
top: 0;
height: 370px;
width: 100%;
}
etc etc.
Content from Github, but not the content of the file. What am I doing wrong?
The content of the file in question is included in the returned data. You are getting the full GitHub view of that file, not just the contents.
If you want to download just the file, you need to use the Raw link at the top of the page, which will be (for your example):
https://raw.githubusercontent.com/someguy/brilliant/master/somefile.txt
Note the change in domain name, and the blob/ part of the path is gone.
To demonstrate this with the requests GitHub repository itself:
>>> import requests
>>> r = requests.get('https://github.com/kennethreitz/requests/blob/master/README.rst')
>>> 'Requests:' in r.text
True
>>> r.headers['Content-Type']
'text/html; charset=utf-8'
>>> r = requests.get('https://raw.githubusercontent.com/kennethreitz/requests/master/README.rst')
>>> 'Requests:' in r.text
True
>>> r.headers['Content-Type']
'text/plain; charset=utf-8'
>>> print r.text
Requests: HTTP for Humans
=========================
.. image:: https://travis-ci.org/kennethreitz/requests.png?branch=master
[... etc. ...]
You need to request the raw version of the file, from https://raw.githubusercontent.com.
See the difference:
https://raw.githubusercontent.com/django/django/master/setup.py vs. https://github.com/django/django/blob/master/setup.py
Also, you should probably add a / between your directory and the filename:
>>> getcwd()+'foo.txt'
'/Users/burhanfoo.txt'
>>> import os
>>> os.path.join(getcwd(),'foo.txt')
'/Users/burhan/foo.txt'
Just as an update, https://raw.github.com was migrated to https://raw.githubusercontent.com. So the general format is:
url = "https://raw.githubusercontent.com/user/repo/branch/[subfolders]/file"
E.g. https://raw.githubusercontent.com/earnestt1234/seedir/master/setup.py. Still use requests.get(url) as in Martijn's answer.
Adding a working example ready for copy+paste:
import requests
from requests.structures import CaseInsensitiveDict
url = "https://raw.githubusercontent.com/organization/repo/branch/folder/file"
# If repo is private - we need to add a token in header:
headers = CaseInsensitiveDict()
headers["Authorization"] = "token TOKEN"
resp = requests.get(url, headers=headers)
print(resp.status_code)
(*) If repo is not private - remove the headers part.
Bonus:
Check out this Curl < --> Python-requests online converter.

How can I access view random created folder in flask?

I have implement simple app in flask. I can get data and process it also but how can I get random created folder. In this app, I tried to input some data to text area. When export deck button clicked then the data post to flask. I can get data and generate deck also but unable send generated deck file or redirect to the random folder.
I get the following error.
raise TypeError(
TypeError: The view function did not return a valid response. The function either returned None or ended without a return statement.)
So, How can I implement this? Redirect to new random generated folder or send the generated file as download link.
Thanks
app.py
from flask import Flask, render_template, request, redirect, url_for, flash, send_file, send_from_directory
import image_occ_deck_export
import random, os
app = Flask(__name__)
app.config["CACHE_TYPE"] = "null"
#app.route("/", methods=["GET","POST"])
def home():
if request.method == "POST":
print(request.form['notes'])
notes = request.form['notes']
# random folder
data = request.form['notes']
print(data)
random_f = random.randrange(1 << 30, 1 << 31)
create_random_folder(random_f, data)
else:
return render_template("index.html")
def create_random_folder(random_f, data):
directory = str(random_f)
parent_dir = "static/uploads/"
path = os.path.join(parent_dir, directory)
if not os.path.exists(path):
os.mkdir(path)
random_file = directory + ".txt"
random_deck_name = directory + ".apkg"
file_loc = path + "/" + random_file
deck_loc = path + "/" + random_deck_name
with open(file_loc, 'w') as f:
f.write(str(data))
image_occ_deck_export.exportDeck(file_loc, deck_loc)
return redirect(url_for('uploaded', path=path))
#app.route('/uploaded/<path>', methods=['GET'])
def uploaded():
return render_template("upload.html")
if __name__ == "__main__":
app.run(debug=False)
index.js
function export() {
var textToExport = document.getElementById("noteData").value;
var formData = new FormData();
formData.append("notes", textToExport);
var request = new XMLHttpRequest();
request.open("POST", "/");
request.send(formData);
}
index.html
<html>
<textarea id="noteData"></textarea>
<button onclick="export()">Export Deck</button>
</html>
sample input
cordova-img-occ-note-1602529000819 <img src='art-1851483_640.jpg'></img> <img src='cordova-img-occ-ques-1602529000819.svg'></img> <img src='cordova-img-occ-ans-1602529000819.svg'></img> <img src='cordova-img-occ-orig-1602529000819.svg'></img>
cordova-img-occ-note-1602529001248 <img src='art-1851483_640.jpg'></img> <img src='cordova-img-occ-ques-1602529001248.svg'></img> <img src='cordova-img-occ-ans-1602529001248.svg'></img> <img src='cordova-img-occ-orig-1602529000819.svg'></img>
cordova-img-occ-note-1602529001673 <img src='art-1851483_640.jpg'></img> <img src='cordova-img-occ-ques-1602529001673.svg'></img> <img src='cordova-img-occ-ans-1602529001673.svg'></img> <img src='cordova-img-occ-orig-1602529000819.svg'></img>
image_occ_deck_export.py
The file use to generate anki deck from txt
import random
import genanki
import csv
import traceback
anki_deck_title = "learn"
anki_model_name = "image occ"
model_id = random.randrange(1 << 30, 1 << 31)
def exportDeck(data_filename, deck_filename):
try:
# front side
front = """
{{#Image}}
<div id="io-header">{{Header}}</div>
<div id="io-wrapper">
<div id="io-overlay">{{Question Mask}}</div>
<div id="io-original">{{Image}}</div>
</div>
<div id="io-footer">{{Footer}}</div>
<script>
// Prevent original image from loading before mask
aFade = 50, qFade = 0;
var mask = document.querySelector('#io-overlay>img');
function loaded() {
var original = document.querySelector('#io-original');
original.style.visibility = "visible";
}
if (mask === null || mask.complete) {
loaded();
} else {
mask.addEventListener('load', loaded);
}
</script>
{{/Image}}
"""
style = """
/* GENERAL CARD STYLE */
.card {
font-family: "Helvetica LT Std", Helvetica, Arial, Sans;
font-size: 150%;
text-align: center;
color: black;
background-color: white;
}
/* OCCLUSION CSS START - don't edit this */
#io-overlay {
position:absolute;
top:0;
width:100%;
z-index:3
}
#io-original {
position:relative;
top:0;
width:100%;
z-index:2;
visibility: hidden;
}
#io-wrapper {
position:relative;
width: 100%;
}
/* OCCLUSION CSS END */
/* OTHER STYLES */
#io-header{
font-size: 1.1em;
margin-bottom: 0.2em;
}
#io-footer{
max-width: 80%;
margin-left: auto;
margin-right: auto;
margin-top: 0.8em;
font-style: italic;
}
#io-extra-wrapper{
/* the wrapper is needed to center the
left-aligned blocks below it */
width: 80%;
margin-left: auto;
margin-right: auto;
margin-top: 0.5em;
}
#io-extra{
text-align:center;
display: inline-block;
}
.io-extra-entry{
margin-top: 0.8em;
font-size: 0.9em;
text-align:left;
}
.io-field-descr{
margin-bottom: 0.2em;
font-weight: bold;
font-size: 1em;
}
#io-revl-btn {
font-size: 0.5em;
}
/* ADJUSTMENTS FOR MOBILE DEVICES */
.mobile .card, .mobile #content {
font-size: 120%;
margin: 0;
}
.mobile #io-extra-wrapper {
width: 95%;
}
.mobile #io-revl-btn {
font-size: 0.8em;
}
"""
# back side
back = """
{{#Image}}
<div id="io-header">{{Header}}</div>
<div id="io-wrapper">
<div id="io-overlay">{{Answer Mask}}</div>
<div id="io-original">{{Image}}</div>
</div>
{{#Footer}}<div id="io-footer">{{Footer}}</div>{{/Footer}}
<button id="io-revl-btn" onclick="toggle();">Toggle Masks</button>
<div id="io-extra-wrapper">
<div id="io-extra">
{{#Remarks}}
<div class="io-extra-entry">
<div class="io-field-descr">Remarks</div>{{Remarks}}
</div>
{{/Remarks}}
{{#Sources}}
<div class="io-extra-entry">
<div class="io-field-descr">Sources</div>{{Sources}}
</div>
{{/Sources}}
{{#Extra 1}}
<div class="io-extra-entry">
<div class="io-field-descr">Extra 1</div>{{Extra 1}}
</div>
{{/Extra 1}}
{{#Extra 2}}
<div class="io-extra-entry">
<div class="io-field-descr">Extra 2</div>{{Extra 2}}
</div>
{{/Extra 2}}
</div>
</div>
<script>
// Toggle answer mask on clicking the image
var toggle = function() {
var amask = document.getElementById('io-overlay');
if (amask.style.display === 'block' || amask.style.display === '')
amask.style.display = 'none';
else
amask.style.display = 'block'
}
// Prevent original image from loading before mask
aFade = 50, qFade = 0;
var mask = document.querySelector('#io-overlay>img');
function loaded() {
var original = document.querySelector('#io-original');
original.style.visibility = "visible";
}
if (mask === null || mask.complete) {
loaded();
} else {
mask.addEventListener('load', loaded);
}
</script>
{{/Image}}
"""
# print(self.fields)
anki_model = genanki.Model(
model_id,
anki_model_name,
fields=[{"name": "id"},{"name": "Header"}, {"name": "Image"}, {"name": "Question Mask"}, {"name": "Footer"}, {"name": "Remarks"}, {"name": "Sources"}, {"name": "Extra 1"}, {"name": "Extra 2"}, {"name": "Answer Mask"}, {"name": "Original"}],
templates=[
{
"name": "Card 1",
"qfmt": front,
"afmt": back,
},
],
css=style,
)
anki_notes = []
with open(data_filename, "r", encoding="utf-8") as csv_file:
csv_reader = csv.reader(csv_file, delimiter="\t")
for row in csv_reader:
flds = []
for i in range(len(row)):
flds.append(row[i])
anki_note = genanki.Note(
model=anki_model,
fields=flds,
)
anki_notes.append(anki_note)
random.shuffle(anki_notes)
anki_deck = genanki.Deck(model_id, anki_deck_title)
anki_package = genanki.Package(anki_deck)
for anki_note in anki_notes:
anki_deck.add_note(anki_note)
anki_package.write_to_file(deck_filename)
print("Deck generated with {} flashcards".format(
len(anki_deck.notes)))
except Exception:
traceback.print_exc()
create_random_folder() returns a redirect, but when you call it from your home() request handler, you don’t do anything with the returned value and you don’t return a response in that code branch of your home() handler. It seems you intend to return that redirect from your home() handler like so:
return create_random_folder(random_f, data)
Remember, when you return a value from a function, you’re returning the value to the calling code, not to the browser. If you call a function from a request handler and receive a return value, that doesn’t automatically get sent back to the browser; you need to return it from the request handler.

How to render a 3D object to HTML file by using pythonOCC in Django?

I have a Django application and I'm using pythonOCC package in it. I have to display the 3D .stl, .stp, .igs files in my template. Normally, when I call the render() function, the following outputs appear on my vscode console and since flask app created by pythonocc instead of django starts running in localhost, my index.html is never rendered. However I need to display the files in a Django template. That's why I have extended the X3DomRenderer Class such as below.
My custom X3DomRenderer class:
class CustomX3DomRenderer(x3dom_renderer.X3DomRenderer):
def render_to_string(self):
self.generate_html_file(self._axes_plane, self._axes_plane_zoom_factor)
return open(self._html_filename, 'r').read()
the HTML codes that returned from render_to_string() function:
<html lang="en">
<head>
<title>pythonOCC 7.4.0 x3dom renderer</title>
<meta name='Author' content='Thomas Paviot - tpaviot#gmail.com'>
<meta name='Keywords' content='WebGl,pythonOCC'>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="https://x3dom.org/release/x3dom.css">
<script src="https://x3dom.org/release/x3dom.js"></script>
<style>
body {
background: linear-gradient(#ced7de, #808080);
margin: 0px;
overflow: hidden;
}
#pythonocc_rocks {
padding: 5px;
position: absolute;
left: 1%;
bottom: 2%;
height: 38px;
width: 280px;
border-radius: 5px;
border: 2px solid #f7941e;
opacity: 0.7;
font-family: Arial;
background-color: #414042;
color: #ffffff;
font-size: 14px;
opacity: 0.5;
}
#commands {
padding: 5px;
position: absolute;
right: 1%;
top: 2%;
height: 65px;
width: 180px;
border-radius: 5px;
border: 2px solid #f7941e;
opacity: 0.7;
font-family: Arial;
background-color: #414042;
color: #ffffff;
font-size: 14px;
opacity: 0.5;
}
a {
color: #f7941e;
text-decoration: none;
}
a:hover {
color: #ffffff;
}
</style>
</head>
<body>
<x3d id="pythonocc-x3d-scene" style="width:100%;border: none" >
<Scene>
<transform scale="1,1,1">
<transform id="plane_smallaxe_Id" rotation="1 0 0 -1.57079632679">
<inline url="https://rawcdn.githack.com/x3dom/component-editor/master/static/x3d/plane.x3d" mapDEFToID="true" namespaceName="plane"></inline>
<inline url="https://rawcdn.githack.com/x3dom/component-editor/master/static/x3d/axesSmall.x3d" mapDEFToID="true" namespaceName="axesSmall"></inline>
</transform>
<inline url="https://rawcdn.githack.com/x3dom/component-editor/master/static/x3d/axes.x3d" mapDEFToID="true" namespaceName="axes"></inline>
</transform>
<transform id="glbal_scene_rotation_Id" rotation="1 0 0 -1.57079632679"> <Inline onload="fitCamera()" mapDEFToID="true" url="shp6b8ef6d6e61744489de16a6798cfe998.x3d"></Inline>
</transform> </Scene>
</x3d>
<div id="pythonocc_rocks">
pythonocc-7.4.0 x3dom renderer
<br>Check our blog at
<a href=http://www.pythonocc.org>http://www.pythonocc.org</a>
</div>
<div id="commands">
<b>t</b> view/hide shape<br>
<b>r</b> reset view<br>
<b>a</b> show all<br>
<b>u</b> upright<br>
</div>
<script>
var selected_target_color = null;
var current_selected_shape = null;
var current_mat = null;
function fitCamera()
{
var x3dElem = document.getElementById('pythonocc-x3d-scene');
x3dElem.runtime.fitAll();
}
function select(the_shape) // called whenever a shape is clicked
{
// restore color for previous selected shape
if (current_mat) {
current_mat.diffuseColor = selected_target_color;
}
// store the shape for future process
current_selected_shape = the_shape;
console.log(the_shape);
// store color, to be restored later
appear = current_selected_shape.getElementsByTagName("Appearance")[0];
mat = appear.getElementsByTagName("Material")[0];
current_mat = mat;
console.log(mat);
selected_target_color = mat.diffuseColor;
mat.diffuseColor = "1, 0.65, 0";
//console.log(the_shape.getElementsByTagName("Appearance"));//.getAttribute('diffuseColor'));
}
function onDocumentKeyPress(event) {
event.preventDefault();
if (event.key=="t") { // t key
if (current_selected_shape) {
if (current_selected_shape.render == "true") {
current_selected_shape.render = "false";
}
else {
current_selected_shape.render = "true";
}
}
}
}
// add events
document.addEventListener('keypress', onDocumentKeyPress, false);
</script>
</body>
</html>
and here is my view:
def occ_viewer(request):
shape = read_step_file(os.path.join('C:/Users/imgea/desktop/bgtask/bgtask/ThreeDFile', 'splinecage.stp'))
my_renderer = extend_x3dom.CustomX3DomRenderer(path='C:/Users/imgea/desktop/bgtask/bgtask/ThreeDFile')
my_renderer.DisplayShape(shape)
context = {'viewer': my_renderer.render_to_string()}
return render(request, 'success.html', context)
and I have added these HTML codes that I got from render_to_string() function to my template file. The viewer's grid has shown but the 3D object hasn't because of the error below.
Page not found: http://127.0.0.1:8000/file/occview/shp6b8ef6d6e61744489de16a6798cfe998.x3d
The library creates that .x3d file in the same directory with the file that I wanna render to template but I guess the viewer is looking for this .x3d file in the error which I mentioned before even I sent the directory. I couldn't find the cause of this error. Am I missing something?
Thank you!!

Brython: Moving Elements Every [...] Microseconds

Good night. This is a question about Brython and any help will be welcome.
I'm looking for a way of moving elements (for example, a div) some pixels to the left (or to the right, top etc.) every time interval (perhaps 200 milliseconds). Can anyone help me?
And it would be great to delete the element once he arrived on the left margin. (:
[update] Here's a starting point. I won't polute it with wrong brython code, follow your creativity ;)
<html><head>
<style>
* { margin: 0; padding: 0; outline: 0; border: 0; }
.block {
display: inline-block;
margin: 1em;
padding: 1em;
background: steelblue;
color: white;
font: 14pt/1.2 georgia,cambria;
border-radius: .2em;
}
</style></head><body>
<div class="block">
Test
</div>
</body></html>
Here is how you can do it :
<html>
<head>
<meta charset="utf-8">
<style>
* { margin: 0; padding: 0; outline: 0; border: 0; }
.block {
display: inline-block;
/*margin: 1em;*/
padding: 1em;
background: steelblue;
color: white;
font: 14pt/1.2 georgia,cambria;
border-radius: .2em;
}
</style>
<script src="/src/brython.js"></script>
<script type="text/python">
import time
elt = doc["moving"]
def move():
elt.style.left = "%spx" %(elt.left+10)
if(elt.left > 500):
time.clear_interval(timer)
del doc["moving"]
timer = time.set_interval(move,200)
</script>
</head>
<body onload="brython(1)">
<div class="block" id="moving" style="position:absolute;top:10;left:20;">
Test
</div>
</body>
</html>
Pretty straightforward, eh ? A few comments :
the DIV element must be set with position = absolute
in the Brython program, you get a reference to the object by doc[object_id] (doc is a built-in name for the document). To delete the object : del doc[object_id]
this object has an attribute left : an integer measuring the distance to the document left border
set_interval and clear_interval are methods added to the built-in module time, they have the same syntax as their Javascript equivalents

How do I specify a header/footer for html2pdf to use when rendering a pdf?

I'm using the html2pdf python library, and would like to define a header and a footer to apply to each page (including fun things, like a page count for the footer). What is the most expedient method I can use to specify headers/footers with html2pdf?
See if this is what needs friend. The header and footer is fixed and informs the count of pages.
<?php
/**
* HTML2PDF Librairy - example
*
* HTML => PDF convertor
* distributed under the LGPL License
*
* #author Laurent MINGUET <webmaster#html2pdf.fr>
*
* isset($_GET['vuehtml']) is not mandatory
* it allow to display the result in the HTML format
*/
ob_start();
// HTML template begin (no output)
?>
<style type="text/css">
<!--
table.page_header {width: 100%; border: none; background-color: #DDDDFF; border-bottom: solid 1mm #AAAADD; padding: 2mm }
table.page_footer {width: 100%; border: none; background-color: #DDDDFF; border-top: solid 1mm #AAAADD; padding: 2mm}
div.niveau
{
padding-left: 5mm;
}
-->
</style>
<page backtop="14mm" backbottom="14mm" backleft="10mm" backright="10mm" style="font-size: 12pt">
<page_header>
<table class="page_header">
<tr>
<td style="width: 100%; text-align: left;">
Exemple d'utilisation des bookmarks
</td>
</tr>
</table>
</page_header>
<page_footer>
<table class="page_footer">
<tr>
<td style="width: 100%; text-align: right">
page [[page_cu]]/[[page_nb]]
</td>
</tr>
</table>
</page_footer>
</page>
<?php
// HTML end
// Getting the html which was not displayed into $content var
$content = ob_get_clean();
require_once(dirname(__FILE__).'/../html2pdf.class.php');
try
{
$html2pdf = new HTML2PDF('P', 'A4', 'fr', true, 'UTF-8', 0);
$html2pdf->writeHTML($content, isset($_GET['vuehtml']));
$html2pdf->createIndex('Sommaire', 25, 12, false, true, 1);
$html2pdf->Output('bookmark.pdf');
}
catch(HTML2PDF_exception $e) {
echo $e;
exit;
}
Easy Blueberry! You can use pages and frames to define headers and footers by placing them in your HTML doc's style tag.
<html>
<head>
<style>
/* Page margins are defined using CSS */
#page {
margin: 1cm;
margin-top:2.5cm;
margin-bottom: 2.5cm;
/* Header frame starts within margin-top of #page */
#frame header {
-pdf-frame-content: headerContent; /* headerContent is the #id of the element */
top: 1cm;
margin-left: 1cm;
margin-right:1cm;
height:1cm;
}
/* Footer frame starts outside margin-bottom of #page */
#frame footer {
-pdf-frame-content: footerContent;
bottom: 2cm;
margin-left: 1cm;
margin-right: 1cm;
height: 1cm;
}
}
</style>
</head>
<body>
<div id="headerContent">I'm a header!</div>
<p>I could be some content</p>
<div id="footerContent">I'm a footer! <pdf:pagenumber></div>
</body>
</html>
pdf:pagenumber is a tag used to display page count. There are many more tags included. Just refer to the official documentation!
Source: HTML2PDF Github Documentation

Categories