i´m trying to render PDF with renderpdf grails plugin,
but their documentation is very short.
i made a button in my gsp view/file
<button type="button">PDF Me!</button>
and
ByteArrayOutputStream bytes = pdfRenderingService.render(template: "/pdfs/report", model: [data: data])
in a view for binding images
<rendering:inlinePng bytes="${imageBytes}" class="some-class" />
model data is domainInstance and how do i connect the button with this renderpdf?
may be i should more specify my code
def invoice ={
def vermittlungInstance = Vermittlung.get(params.id)
def aa = vermittlungInstance.lieferungen.id
def lieferungInstance = Lieferung.get(aa)
def bb = lieferungInstance.packete.id // .id
def packetInstance = Packet.findAllByIdInList(bb)
if (!vermittlungInstance & !lieferungInstance) {
flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'vermittlung.label', default: 'Vermittlung'), params.id])}"
redirect(action: "list")
}
else {
if(vermittlungInstance.rechnungen.id!=null || vermittlungInstance.lieferungen.id!=null || lieferungInstance.packete.id!=null ){
def a = vermittlungInstance.rechnungen.id
def rechnungList = Rechnung.findById(a)
def b = vermittlungInstance.lieferungen.id
def lieferungList = Lieferung.findById(b)
def c = lieferungInstance.packete.id
//println c
def packetList = Packet.findAllByIdInList(c)//findById(c)
def d = packetInstance.artikel.id//id
def artikelList = Artikel.findAllByIdInList(d)//findById(d)
def e = lieferungInstance.adressen.id
def adresseList = Adresse.findById(e)
[vermittlungInstance: vermittlungInstance,
rechnungInstanceList:rechnungList,
lieferungInstanceList:lieferungList,
packetInstanceList: packetList,
artikelInstanceList: artikelList,
adresseInstanceList: adresseList
]
//System.out.println(c)
}
else{
def rechnungList = Rechnung.all
def lieferungList = Lieferung.all
def packetList = Packet.all
def artikelList = Artikel.all
def adresseList = Adresse.all
[vermittlungInstance: vermittlungInstance,
rechnungInstanceList:rechnungList,
lieferungInstanceList:lieferungList,
packetInstanceList: packetList,
artikelInstanceList: artikelList,
adresseInstanceList: adresseList
]
}
}
}
this is my def in a controller, i tried to put this renderpdf on many places, but it won't render the page, actually i am changing some values in html (browser), so it should render in html.
the controller seems to be a wrong place to renderpdf than, but there is no render function for .gsp
thanks
Add a new action which generates the pdf version of your invoice and link them from your view.
Here is your link:
<g:link action="downloadInvoice" id="${yourInvoiceID}">Download invoice</g:link>
In your controlle add following:
def downloadInvoice = {
def invoice = Invoice.get(params.id) //replace with your logic
renderPdf(template: '/templates/pdf/invoice', model: [invoice: invoice], filename: "yourTitle")
}
Your invoice template is a simple gsp view where you could place all your HTML (including images) and CSS:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Invoice</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" href="${resource(dir:'css',file:'your.css')}" />
</head>
<body>
<img src="${resource(dir:'images',file:'invoiceLogo.png')}" />
<h1>Invoice: ${invoice.id}</h1>
.
.
.
</body>
</html>
Hope that example helps!
How to add unicode fonts to this plugin ?? unicode characters are not displayed in rendered pdf. The generated pdf contains blank spaces in place of unicode characters, although they are displayed in other gsp pages. later that i tried the below css. but not worked.
#font-face {
font-family: 'Ubuntu';
font-style: normal;
font-weight: 400;
src:url(http://themes.googleusercontent.com/static/fonts/ubuntu/v4/_xyN3apAT_yRRDeqB3sPRg.woff) format('woff');
-fs-pdf-font-embed: embed;
-fs-pdf-font-encoding: UTF-8;
}
body pre{
font-size: 14px;
font-family: 'Ubuntu', Helvetica, Arial, sans-serif;
}
Thank you,
Related
This html has 3 divs with the same name accounts-table__count but different types of information.
I'm trying to get the posts count and and follower count of this page. is there a way to take the texts using css selector?
site;https://mastodon.online/explore
<div class='directory__card__extra'>
<div class='accounts-table__count'>
629
<small>posts</small>
</div>
<div class='accounts-table__count'>
72
<small>followers</small>
</div>
<div class='accounts-table__count'>
<time class='time-ago' datetime='2021-05-18' title='May 18, 2021'>May 18, 2021</time>
<small>last active</small>
</div>
</div>
my code;
def parse(self, response):
for users in response.css('div.directory__card'):
yield {
'id': users.css('span::text').get().replace('#','').replace('.','-'),
'name': users.css('strong.p-name::text').get(),
'posts': '' // this is the post count //
'followers': '' // this is the follower count //
'description': users.css('p::text').get(),
'fediverse': users.css('span::text').get(),
'link': users.css('a.directory__card__bar__name').attrib['href'],
'image': users.css('img.u-photo').attrib['src'],
'bg-image': users.css('img').attrib['src'],
}
for nextpage in response.css('span.next'):
next_page = nextpage.css('a').attrib['href']
if next_page is not None:
yield response.follow(next_page, callback=self.parse)
As example, iterate over card, for each one get the values in shape of text and filter out the values.
raw_data = response.css(".directory__card")[0].css(".accounts-table__count::text").getall()
values = list(filter(lambda s: s != "", map(lambda s: s.strip(), raw_data)))
Some values from css selector of .accounts-table__count::text are empty, because div elements with this class has no text, but other html elements in it.
I have a following Kotlin object type with default null value for a field:
data class Field(
val content: String? = null,
val field: String = ""
)
Then I try to pass the object:
val myObject = Field(field = "something")
to the mustache template:
<!DOCTYPE ...>
<html>
<head>
<meta .../>
</head>
<body ...">
{{#myObject}}
{{#content}}
{{.}}<br/>
{{/content}}
{{#field}}
{{.}}<br/>
{{/field}}
{{/myObject}}
</body>
</html>
And after filling the template I receive an exception: No key, method or field with name 'content' on line ...
I cannot get what can be wrong
may be you should define the "" for the content default for the problem?
I'm having hard time troubleshooting why i cannot seem to run this inside wordpress like on the index.php. It works when its standalone. I created additional table inside wordpress db. Im seeing blank data when i run. Somehow its not picking up the data. I came to know after research i need to use $wpdb and get_results. so I converted it from this old code :
$result = $db->query("SELECT name,rating FROM wp_figure where status = '1' ORDER BY rating DESC");
/to wordpress code/
<?php
global $wpdb;
$results = $wpdb->get_results("SELECT name,rating FROM wp_figure where status = '1' ORDER BY rating DESC");
?>
//on the header.php
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['name', 'Rating'],
<?php
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
echo "['".$row['name']."', ".$row['rating']."],";
}
}
?>
]);
var options = {
title: 'Figure',
width: 900,
height: 500,
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
on the body html i have
<body>
<!-- Display the pie chart -->
<div id="piechart"></div>
</body>
If you are using $wpdb , then you must need to pass 'ARRAY_A' inside get_results like the following to get result in array format.
global $wpdb;
$results = $wpdb->get_results("SELECT name,rating FROM wp_figure where status = '1' ORDER BY rating DESC",'ARRAY_A');
On my site I created two simple pages:
Here are their first html script:
test1.html :
<head>
<title>test1</title>
</head>
<body>
<a href="test2.html" onclick="javascript:return xt_click(this, "C", "1", "Product", "N");" indepth="true">
<span>cool</span></a>
</body></html>
test2.html :
<head>
<title>test2</title>
</head>
<body></body></html>
I want scraping text in the title tag of the two pages.here is "test1" and "test2".
but I am a novice with scrapy I only happens scraping only the first page.
my scrapy script:
from scrapy.spider import Spider
from scrapy.selector import Selector
from testscrapy1.items import Website
class DmozSpider(Spider):
name = "bill"
allowed_domains = ["http://exemple.com"]
start_urls = [
"http://www.exemple.com/test1.html"
]
def parse(self, response):
sel = Selector(response)
sites = sel.xpath('//head')
items = []
for site in sites:
item = Website()
item['title'] = site.xpath('//title/text()').extract()
items.append(item)
return items
How to pass the onclik?
and how to successfully scraping the text of the title tag of the second page?
Thank you in advance
STEF
To use multiple functions in your code, send multiple requests and parse them, you're going to need: 1) yield instead of return, 2) callback.
Example:
def parse(self,response):
for site in response.xpath('//head'):
item = Website()
item['title'] = site.xpath('//title/text()').extract()
yield item
yield scrapy.Request(url="http://www.domain.com", callback=self.other_function)
def other_function(self,response):
for other_thing in response.xpath('//this_xpath')
item = Website()
item['title'] = other_thing.xpath('//this/and/that').extract()
yield item
You cannot parse javascript with scrapy, but you can understand what the javascript does and do the same: http://doc.scrapy.org/en/latest/topics/firebug.html
I'm running nginx 1.2.3 / php-fpm 5.4.6 and trying to use the Session upload progress feature. During an upload $_SESSION never contains any upload data whatsoever. At first I assumed coding errors, but even the most simple/basic upload progress tests failed to produce anything within $_SESSION.
I now suspect that the file is being POSTed directly to nginx, which completely handles the upload from beginning to end, THEN nginx passes the upload on to php-fpm so quickly that there is no real "progress" to report. Am I correct in this assessment? If so, how can I get around this?
phpconfig confirms that the session.upload settings are all set correctly.
Below is the current test code, borrowed from this blog.
<?php
/* File upload progress in PHP 5.4 */
/* needs a 5.4+ version */
$version = explode( '.', phpversion() );
if ( ($version[0] * 10000 + $version[1] * 100 + $version[2]) < 50400 )
die( 'PHP 5.4.0 or higher is required' );
if ( !intval(ini_get('session.upload_progress.enabled')) )
die( 'session.upload_progress.enabled is not enabled' );
session_start();
if ( isset( $_GET['progress'] ) ) {
$progress_key = strtolower(ini_get("session.upload_progress.prefix").'demo');
if ( !isset( $_SESSION[$progress_key] ) ) exit( "uploading..." );
$upload_progress = $_SESSION[$progress_key];
/* get percentage */
$progress = round( ($upload_progress['bytes_processed'] / $upload_progress['content_length']) * 100, 2 );
exit( "Upload progress: $progress%" );
}
?>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<?php if ( isset($_GET['iframe']) ): /* thank you Webkit... */ ?>
<form action="" method="POST" enctype="multipart/form-data">
<input type="hidden" name="<?php echo ini_get("session.upload_progress.name"); ?>" value="demo">
<input type="file" name="uploaded_file">
<input type="submit" value="Upload">
</form>
<script type="text/javascript">
window.location.hash = ""; /* reset */
jQuery("form").bind("submit", function() { window.location.hash = "uploading"; });
</script>
<?php else: ?>
<iframe src="?iframe" id="upload_form"></iframe>
<script type="text/javascript">
jQuery(document).ready(init);
function init() {
/* start listening on submit */
update_file_upload_progress();
}
function update_file_upload_progress() {
if ( window.frames.upload_form.location.hash != "#uploading" ) {
setTimeout( update_file_upload_progress, 100 ); /* has upload started yet? */
return;
}
$.get( /* lather */
"?progress",
function(data) {
/* rinse */
jQuery("#file_upload_progress").html(data);
/* repeat */
setTimeout( update_file_upload_progress, 500 );
}
).error(function(jqXHR, error) { alert(error); });
}
</script>
<div id="file_upload_progress"></div>
<?php endif; ?>
A note in the documentation page on php.net says :
s.zarges 19-Jun-2012 09:32
Note, this feature doesn't work, when your webserver is runnig PHP via FastCGI. There will be no progress informations in the session array.
Unfortunately PHP gets the data only after the upload is completed and can't show any progress.