I have an html document that I'm converting to pdf with PDFKit and wkhtmltopdf. It's rendering fine, but I need to specify a different background for the second and subsequent pages. In other words, the first page will have one background, and the other pages will have a different one.
I have tried implementing javascript like so:
var pdfInfo = {};
var x = document.location.search.substring(1).split('&');
for (var i in x) { var z = x[i].split('=',2); pdfInfo[z[0]] = unescape(z[1]); }
function switchBackground(){
if (pdfInfo.page>1){ document.body.style.backgroundColor = "#333"; }
}
This does not work.
All pages in output PDF have the same body. So you have to use extra wrappers for each page and something like this:
section:nth-child(odd) {
background-color: #ccc;
}
Related
In C# I'm trying to pass in a simple HTML string and have the string parsed and added to a PDF document. In the below examples, I'm adding the string to an iText7 Paragraph.
I read this article and managed to write the below code.
https://itextpdf.com/en/resources/books/itext-7-converting-html-pdf-pdfhtml/chapter-1-hello-html-pdf
The first paragraph (p1), Example 1, renders the correct font face, Helvetica. Of course, I'm using the SetAction method, which is completely a different approach than the article. This is for demo purposes only.
The second paragraph (p2), Example 2, converts the HTML just fine but the font for the word "link" is rendered differently than Helvetica. It seems that when HTML is rendered, it ignores the font face of the document.
Sample Screenshot
How can I get the font face of "link" to be Helvetica and use the approach in Example 2? I think I'm missing something minor here. Do I need to define a CSS class since we're in HTML land?
Thank you for any suggestions.
class Program
{
static void Main(string[] args)
{
var pdfWriter = new PdfWriter(#"c:\temp\test.pdf");
var pdfDocument = new PdfDocument(pdfWriter);
var document = new Document(pdfDocument);
// Example 1
var p1 = new Paragraph("p1: this is a test url")
.SetFont(PdfFontFactory.CreateFont(StandardFonts.HELVETICA))
.SetFontSize(12f)
.SetFontColor(new DeviceCmyk(1f, .31f, 0, 0))
.SetFixedPosition(35, 600, UnitValue.CreatePercentValue(100f))
.SetAction(PdfAction.CreateURI("www.google.com"));
document.Add(p1);
// Example 2
var html = #"p2: this is a test url";
var elements = HtmlConverter.ConvertToElements(html);
var p2 = new Paragraph()
.SetFont(PdfFontFactory.CreateFont(StandardFonts.HELVETICA))
.SetFontSize(12f)
.SetFontColor(new DeviceCmyk(1f, .31f, 0, 0))
.SetFixedPosition(35, 550, UnitValue.CreatePercentValue(100f));
foreach (var element in elements)
{
p2.Add((IBlockElement)element);
}
document.Add(p2);
document.Close();
pdfDocument.Close();
pdfWriter.Close();
}
}
The default font-family in pdfHTML is Times, and you are overriding it only for the top-level elements while (almost) all the elements at all nesting levels have their font family explicitly specified after ConvertToElements invocation. To change the font family the easiest solution is indeed apply some CSS to your initial HTML. You can set font-family in style declaration directly:
var html = #"<p style=""font-family: Helvetica"">p2: this is a test url</p>";
Then you don't even have to set font to your paragraph and the paragraph creation code simplifies to
var p2 = new Paragraph()
.SetFontSize(12f)
.SetFontColor(new DeviceCmyk(1f, .31f, 0, 0))
.SetFixedPosition(35, 550, UnitValue.CreatePercentValue(100f));
foreach (var element in elements)
{
p2.Add((IBlockElement)element);
}
I am working with Telerik Word Processing (WP) and in some instances the HTML output on screen has a line strike through to show that an event is cancelled.
Because of how the WP works, it cannot use CSS in the standard way using links and relative paths so am using style tags in the CSHTML file.
If in the page I use
.cancelled-event {
color: #c82333;
text-decoration: underline !important
}
The text is underlined and is coloured correctly, if I use
.cancelled-event {
color: #c82333;
text-decoration: line-through !important
}
I just get the text the right colour.
Overline also does not work, however only tested this to ensure that Im not being an idiot (doesn't mean Im not, but still one of the easy checkables)
What I would like help with is,
Has anyone else experienced this? If so how did you resolve it,
What other suggestions, is there to get
The CSHTML page is as below, munis code that will bloat this question.
<style>
.date-selection {
border: 1px solid #8c8c8c;
background-color: #ffffff
}
.cancelled-event {
color: #c82333;
text-decoration: line-through !important
... more styles here...
}
</style>
<img src="http://localhost:8001/images/logo.png" />
<br/>
<partial name="~/Views/Roster/_RosterAgenda.cshtml" model="#Model" />
I konw the strike through does show in 2/3 scenarios.
In view - works
In view where export should be as I have an exit where I can push the data to a view before pdf - works
In PDF - doesnt work.
PDF Generation is being done like this, the byte array that is passed in is base 64 encoded as the original file information is being passed from one System to an API over the wire.
public byte[] ConvertHtmlToPdf(byte[] fileData, string extension, PageSettings.PageOrientation orientation)
{
byte[] convertedData = null;
var base64EncodedBytes = Convert.FromBase64String(Encoding.Default.GetString(fileData));
var html = Encoding.UTF8.GetString(base64EncodedBytes);
HtmlFormatProvider htmlProvider = new HtmlFormatProvider();
RadFlowDocument document = htmlProvider.Import(html);
IFormatProvider<RadFlowDocument> provider = this.providers
.FirstOrDefault(p => p.SupportedExtensions
.Any(e => string.Compare(extension, e, StringComparison.InvariantCultureIgnoreCase) == 0));
if (provider == null)
{
Log.Error($"No provider found that supports the extension: {extension}");
return null;
}
var quality = Telerik.Windows.Documents.Fixed.FormatProviders.Pdf.Export.ImageQuality.Medium;
PdfFormatProvider formatProvider = new PdfFormatProvider();
formatProvider.ExportSettings.ImageQuality = quality;
if (document.Sections.Any())
{
foreach (var section in document.Sections)
{
//section.PageOrientation = orientation == PageSettings.PageOrientation.Landscape ? PageOrientation.Landscape : PageOrientation.Portrait;
section.Rotate(orientation == PageSettings.PageOrientation.Landscape ? PageOrientation.Landscape : PageOrientation.Portrait);
}
}
using (var stream = new MemoryStream())
{
formatProvider.Export(document, stream);
convertedData = stream.ToArray();
}
return convertedData;
}
I found a better, easier, nicer way, but this only works if you have the Kendo Tools license too.
$(".export-pdf").click(function() {
// Convert the DOM element to a drawing using kendo.drawing.drawDOM
kendo.drawing.drawDOM($(".content-wrapper"))
.then(function(group) {
// Render the result as a PDF file
return kendo.drawing.exportPDF(group, {
paperSize: "auto",
margin: { left: "1cm", top: "1cm", right: "1cm", bottom: "1cm" }
});
})
.done(function(data) {
// Save the PDF file
kendo.saveAs({
dataURI: data,
fileName: "HR-Dashboard.pdf",
proxyURL: "https://demos.telerik.com/kendo-ui/service/export"
});
});
});
As per usual Telerik documentation is awful, and to find anything you want you almost have to start looking for something else. However, this code was found at
https://www.telerik.com/blogs/5-ways-export-asp-net-word-pdf-file
The benefit of this, and once again this only works if you have UI for xxx. In this instance I am using UI for ASP.Net Core and also using Typescript which needed a modification to the definately typed file kendo.all.d.ts too.
function drawDOM(element: JQuery, options: any): JQueryPromise<any>; //Existing code in the d.ts file
function drawDOM(element: JQuery<HTMLElement>);
function drawDOM(element: any, options?: any): JQueryPromise<any>;
But this is \ was down to not passing in a type of jquery object of HTMLElement. This makes it a little more robust enabling you to pass more into it.
I suspect that this answer will only be of use to a small number of people, however, hopefully this will help someone in the future.
I wrote a script to add an image from my Google Drive and some custom text to a Google Doc. (I got the image insertion code from here).
The resulting document is created ok, but my image is added twice for some reason...
function myFunction(e) {
var doc = DocumentApp.create('fileTest');
var body = doc.getBody();
var matchedFiles = DriveApp.getFilesByName('logo.png');
if (matchedFiles.hasNext()) {
var image = matchedFiles.next().getBlob();
var positionedImage = body.getParagraphs()[0].addPositionedImage(image);
}
body.appendParagraph('Test line of text for testing');
doc.saveAndClose();
}
However, if I get rid of my appendParagraph code (body.appendParagraph(t1);) I only get one image (but obviously without the paragraph of text I want)
What's going on here? And how do I add both one picture and my paragraph of text?
I have not even the slightest clue as to why, but I found a way to make this work.
Switching the order of my code seemed to do the trick. I simply moved the image-insertion code to the end (i.e., after the appendParagraph code), and it worked fine. No duplicate image!
function myFunction(e) {
var doc = DocumentApp.create('fileTest');
var body = doc.getBody();
body.appendParagraph('Test line of text for testing');
var matchedFiles = DriveApp.getFilesByName('logo.png');
if (matchedFiles.hasNext()) {
var image = matchedFiles.next().getBlob();
var positionedImage = body.getParagraphs()[0].addPositionedImage(image);
}
doc.saveAndClose();
}
I need to hide all the images on the page So I wrote this code :
var imagesVisibility = document.getElementsByTagName('img');
for (var i = 0; i < imagesVisibility.length; i++) {
imagesVisibility[i].style.visibility = 'hidden';
}
It works great but I can not hide the images are defined via CSS.
How do I hide all images on a page are defined via CSS?
You can look into the jQuery, which has a css method which lets you alter the styles of a selected element:
$(‘#idofthediv’).css({backgroundImage:’none’});
I have an HTML5 canvas which is displaying a number of images. I also have some simple HTML <p></p> tags on my page below the canvas.
I want to update the contents of the <p></p> tags when the cursor hovers over these images, and I found a quick tutorial at: http://www.quirksmode.org/js/newmouseover.html which seemed to suggest it could teach you how to do this.
I've followed the tutorial, however, when I view my page in the browser now, I get a console error that says
getElementByTagName is not a function
I've not seen this function before, and I'm just wondering if it is actually a pre-defined function, or if it's one that the writer of the tutorial has defined themselves...? I couldn't see anything on that page where the author has defined the function, so I thought it might be a pre-defined one, but I'm not sure. Does anyone know?
Edit
Ok, so correcting the typo fixed it, and the function is now being called. However, I'm currently calling it from my window.onload function, so as soon as the page loads, the paragraph has already been updated- it's not actually conditional on the onmouseover event being called.
My window.onload function looks like this:
window.onload = function () {
var sources = [];
sources[0] = document.getElementById("building").src,
sources[1] = document.getElementById("chair").src,
sources[2] = document.getElementById("drink").src,
sources[3] = document.getElementById("food").src,
/*There are roughly 30 lines like this adding images in the same way */
if (document.getElementById) {
var x = document.getElementById('mouseovers')
.getElementsByTagName('IMG');
} else if (document.all) {
var x = document.all['mouseovers'].all.tags('IMG');
} else {
return;
}
for (var i = 0; i < x.length; i++) {
console.log("for loop adding onmouseovers is being called");
x[i].onmouseover = displayAssetDescriptionTip();
}
loadImages(sources, drawImage);
drawGameElements();
drawDescriptionBoxes();
stage.add(imagesLayer);
};
I tried moving the if statements into a function called displayAssetDescriptionTip(), and this function now looks like this:
function displayAssetDescriptionTip() {
if (document.getElementById) {
var x = document.getElementById('mouseovers')
.getElementsByTagName('IMG');
} else if(document.all) {
var x = document.all['mouseovers'].all.tags('IMG');
}else {
return;
}
for (var i = 0; i < x.length; i++) {
console.log("for loop adding onmouseovers is being called");
x[i].onmouseover = displayAssetDescriptionTip();
}
document.getElementById('tipsParagraph').innerHTML = "Assets are items that"
+ " can be bought or sold for cash.";
console.log("displayAssetDescriptionTip being called");
}
However, the onmouseover event doesn't appear to be firing when I hover the cursor over the images to which it's been added- any ideas why this is?
getElementByTagName is not a function.
getElementsByTagName is though :)
It's plural because it returns every element that matches the given tag.