How to add Sig Field to jsPDF for digital signature - jspdf

I would like to use node-signpdf to digitally sign a pdf document,
Their example uses pdfkit library and shows how to add a (digital) signature placeholder using the ref function to create PDF reference where pdf if pdfkit
export const addSignaturePlaceholder = ({pdf, reason, signatureLength = 8192}) => {
/* eslint-disable no-underscore-dangle,no-param-reassign */
// Generate the signature placeholder
const signature = pdf.ref({
Type: 'Sig',
Filter: 'Adobe.PPKLite',
SubFilter: 'adbe.pkcs7.detached',
ByteRange: [
0,
DEFAULT_BYTE_RANGE_PLACEHOLDER,
DEFAULT_BYTE_RANGE_PLACEHOLDER,
DEFAULT_BYTE_RANGE_PLACEHOLDER,
],
Contents: Buffer.from(String.fromCharCode(0).repeat(signatureLength)),
Reason: new String(reason), // eslint-disable-line no-new-wrappers
M: new Date(),
});
Using the placeholder to store the actual hash signature of the pdf as a buffer.
What I am missing is the way to do it using jsPDF.
Any idea or code snippet will be appreciated.

Related

playwirght - drag and drop files

I'm looking at automating a drag and drop scenario using Playwright. I found this code which is meant to do just this:
// Read your file into a buffer.
const buffer = readFileSync('./runtime_config/common/file.pdf');
// Create the DataTransfer and File
const dataTransfer = await scope.page.evaluateHandle((data) => {
const dt = new DataTransfer();
// Convert the buffer to a hex array
const file = new File([data.toString('hex')], 'file.pdf', { type: 'application/pdf' });
dt.items.add(file);
return dt;
}, buffer);
// Now dispatch
await page.dispatchEvent('YOUR_TARGET_SELECTOR', 'drop', { dataTransfer });
This code was found on this github post https://github.com/microsoft/playwright/issues/10667
When I try to use this code, I get an error that 'scope is not defined'
I can't see how this would work, nor does the post have any info. I've reached out to the poster but no reply yet, so thought I'd try here. Anyone know how this would work?
(I tried modify the line to be this.page.evaluateHandle((data) which doesn't error at runtime, but all I am getting is a 15B file called 'file.pdf' in the UI. I have console.log the buffer and it does appear to be valid.)

Invalid value for transfer while using ipcRenderer.postMessage of electron

Invalid value for transfer while using ipcRenderer.postMessage of electron?I don't know what's wrong with it
// eslint-disable-next-line no-undef
const { port1 } = new MessageChannel();
// eslint-disable-next-line no-undef
ipcRenderer.postMessage('port', { message: 'hello' }, [port1]);
I wonder if something wrong in my preload.js?
I upload all my code to github
https://github.com/codeh2o/electronVuePreloadIssue

konvajs serialize stage containing images

I'm creating a custom label maker using Konvajs and everything was working perfectly until I tried to serialize the stage to JSON.
The user creates their custom label in three steps. The first step they select a template image from our library that has a masked area. The second step allows them to upload a personalized image that is placed behind the image that was loaded on the first step. There are external controls that allow the user to scale and move the image so it is rendered with in the masked area. The third step allows them to add text.
I want the user to be able to save their label to their library so they can use it again, but be able to modify any of the three steps. This means I need to serialize the stage to a JSON string, but the image attributes aren't saved in the JSON.
JSON String:
{"attrs":{"width":500,"height":667,"id":"label-maker"},"className":"Stage","children":[{"attrs":{},"className":"Layer","children":[{"attrs":{"name":"template"},"className":"Image"}]},{"attrs":{},"className":"Layer","children":[{"attrs":{"x":160,"y":41.5,"text":"[Enter Name Here]","fontSize":30,"fontFamily":"Calibri","fill":"#555","name":"textundefined","align":"center","draggable":true,"offsetX":114.22119140625},"className":"Text"}]}]}
I'm using the Konvajs toJSON() to serialize my stage.
function save() {
var json = stage.toJSON();
var dataURL = stage.toDataURL('image/png');
//alert(json);
$.ajax({
type: "POST",
url: "label-maker/image-handler.php?action=save",
data: {jsonFileText: json, image: dataURL},
error: function (request, error) {
console.log(arguments);
alert(" Can't do because: " + error);
},
success: function () {
alert(" Done ! ");
}
});
}
By default Konva doesn't save information about image source to JSON. So you have to do this manually.
When you create Konva.Image you can save its source as attribute:
// path is url or base64 string from user's input
imageNode.setAttr('src', path);
Then on deserialization you can load image data from source:
const stage = Konva.Node.create(json, 'container');
stage.find('Image').forEach((imageNode) => {
const src = imageNode.getAttr('src');
const image = new Image();
image.onload = () => {
imageNode.image(image);
imageNode.getLayer().batchDraw();
}
image.src = src;
});

How to paste plain text in a Quill-based editor

Quill (https://quilljs.com/) makes it simple to embed a quality text editor in a web page. When pasting html content in the editor, it filters the pasted html and then puts it into the text editor. My question is: How can I configure Quill so it pastes only plain text in the text editor? It would filter out all tags and leave the plain text only.
The documentation about the Clipboard module (http://quilljs.com/docs/modules/clipboard/) says that it is possible to add custom Matchers to the Clipboard, that will kind of filter the pasted text.
I don't know how to write a matcher that only allows plain text. Any help and any examples are much appreciated - thanks!
After trial and error, I found the answer. The following matcher will cause the editor to paste plain text only:
quill.clipboard.addMatcher (Node.ELEMENT_NODE, function (node, delta) {
var plaintext = $ (node).text ();
return new Delta().insert (plaintext);
});
It uses jQuery. :)
Couldn't get the answer to work. Here's another method that patches the clipboard module to accept plain text only.
GitHub Gist:
https://gist.github.com/prodrammer/d4d205594b2993224b8ad111cebe1a13
Clipboard implementation:
import Quill from 'quill'
const Clipboard = Quill.import('modules/clipboard')
const Delta = Quill.import('delta')
class PlainClipboard extends Clipboard {
onPaste (e) {
e.preventDefault()
const range = this.quill.getSelection()
const text = e.clipboardData.getData('text/plain')
const delta = new Delta()
.retain(range.index)
.delete(range.length)
.insert(text)
const index = text.length + range.index
const length = 0
this.quill.updateContents(delta, 'silent')
this.quill.setSelection(index, length, 'silent')
this.quill.scrollIntoView()
}
}
export default PlainClipboard
Example usage:
import Quill from 'quill'
import PlainClipboard from './PlainClipboard'
Quill.register('modules/clipboard', PlainClipboard, true)
Updated solution of teusbenschop - works without jQuery and also fix problem with missing Delta object.
quill.clipboard.addMatcher (Node.ELEMENT_NODE, function (node, delta) {
var plaintext = node.innerText
var Delta = Quill.import('delta')
return new Delta().insert(plaintext)
})
For the googlers;
I created a Quill plugin, that removes all tags and attributes that are not supported. Unless otherwise configured it detects that by looking into the toolbar module.
I thought I post it here so others will not have to struggle :)
https://www.npmjs.com/package/quill-paste-smart
import Quill from 'quill';
quill.clipboard.addMatcher(Node.ELEMENT_NODE, function (node, delta) {
const plaintext = node.innerText
const Delta = Quill.import('delta')
return new Delta().insert(plaintext)
});

Generating pdf from html using Prawn

I want to generate pdf from html. A gem prawn seems to be the most popular one for that. I downloaded the manual for it, but there is no information about how to generate pdf from html.
In particular, I need it to work on Heroku also, but that's the second goal.
So how can I generate pdf from html using Prawn?
Look for Pdfkit, it's second most popular gem RubyToolbox. It generate PDF from HTML using wkhtmltopdf. On RailsCasts is one older tutorial.
This is a sample code to generate pdf from html using prawn
/// <summary>
/// Convert the HTML code from the specified URL to a PDF document
and send the document to the browser
/// </summary>
private void ConvertURLToPDF()
{
string urlToConvert = textBoxWebPageURL.Text.Trim();
// Create the PDF converter. Optionally the HTML viewer width can
be specified as parameter
// The default HTML viewer width is 1024 pixels.
PdfConverter pdfConverter = new PdfConverter();
// set the license key - required
pdfConverter.LicenseKey = "R8nYyNnI2MjRxtjI29nG2drG0dHR0Q==";
// set the converter options - optional
pdfConverter.PdfDocumentOptions.PdfPageSize = PdfPageSize.A4;
pdfConverter.PdfDocumentOptions.PdfCompressionLevel = PdfCompressionLevel.Normal;
pdfConverter.PdfDocumentOptions.PdfPageOrientation = PdfPageOrientation.Portrait;
// set if header and footer are shown in the PDF - optional - default
is false
pdfConverter.PdfDocumentOptions.ShowHeader = cbAddHeader.Checked;
pdfConverter.PdfDocumentOptions.ShowFooter = cbAddFooter.Checked;
// set if the HTML content is resized if necessary to fit the PDF
page width - default is true
pdfConverter.PdfDocumentOptions.FitWidth = cbFitWidth.Checked;
// set the embedded fonts option - optional - default is false
pdfConverter.PdfDocumentOptions.EmbedFonts = cbEmbedFonts.Checked;
// set the live HTTP links option - optional - default is true
pdfConverter.PdfDocumentOptions.LiveUrlsEnabled = cbLiveLinks.Checked;
// set if the JavaScript is enabled during conversion to a PDF - default
is true
pdfConverter.JavaScriptEnabled = cbClientScripts.Checked;
// set if the images in PDF are compressed with JPEG to reduce the
PDF document size - default is true
pdfConverter.PdfDocumentOptions.JpegCompressionEnabled = cbJpegCompression.Checked;
// enable auto-generated bookmarks for a specified list of HTML selectors
(e.g. H1 and H2)
if (cbBookmarks.Checked)
{
pdfConverter.PdfBookmarkOptions.HtmlElementSelectors = new string[] { "H1", "H2" };
}
// add HTML header
if (cbAddHeader.Checked)
AddHeader(pdfConverter);
// add HTML footer
if (cbAddFooter.Checked)
AddFooter(pdfConverter);
// Performs the conversion and get the pdf document bytes that can
// be saved to a file or sent as a browser response
byte[] pdfBytes = pdfConverter.GetPdfBytesFromUrl(urlToConvert);
// send the PDF document as a response to the browser for download
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.Clear();
response.AddHeader("Content-Type", "application/pdf");
if (radioAttachment.Checked)
response.AddHeader("Content-Disposition",
String.Format("attachment; filename=GettingStarted.pdf; size={0}",
pdfBytes.Length.ToString()));
else
response.AddHeader("Content-Disposition",
String.Format("inline; filename=GettingStarted.pdf; size={0}",
pdfBytes.Length.ToString()));
response.BinaryWrite(pdfBytes);
// Note: it is important to end the response, otherwise the ASP.NET
// web page will render its content to PDF document stream
response.End();
}

Resources