Flutter creat pdf file with different page size and font size - pdf

Here with the code to create a pdf file for flutter. I am using plugin pdf 1.0.6.
My questions:
How to create a pdf file width 75mm with auto height to fit the
content?
How to create multi lines of text with different font size?
PDFDocument _generateDocument() {
final pdf = new PDFDocument(deflate: zlib.encode);
final page = new PDFPage(pdf, pageFormat: PDFPageFormat.A4);
final g = page.getGraphics();
final font = new PDFFont(pdf);
final top = page.pageFormat.height;
g.setColor(new PDFColor(0.0, 1.0, 1.0));
g.drawRect(50.0 * PDFPageFormat.MM, top - 80.0 * PDFPageFormat.MM,
100.0 * PDFPageFormat.MM, 50.0 * PDFPageFormat.MM);
g.fillPath();
g.setColor(new PDFColor(0.3, 0.3, 0.3));
g.drawString(font, 12.0, "Hello World!", 10.0 * PDFPageFormat.MM,
top - 10.0 * PDFPageFormat.MM);
return pdf;
}

I recommend you to update to the latest version pdf: ^1.4. as a lot has changed on how to build a pdf.
For the format size I would try PdfPageFormat.undefined or in your case PdfPageFormat(75, double.infinity)
https://github.com/DavBfr/dart_pdf/blob/78232de1f962ea04c7e950d0f737417a35863071/pdf/lib/src/page_format.dart#L49
For the multiline with different size I would use the new way of creating a pdf that uses widgets. See the example:
https://github.com/DavBfr/dart_pdf/blob/master/pdf/example/main.dart
As simple as
pdf.addPage(Page(
pageFormat: PdfPageFormat.a4,
build: (Context context) {
return Center(
child: Text('Hello World', style: TextStyle(fontSize: 40)),
); // Center
})); // Page

Related

html2pdf fit image to pdf

I finally got my html2pdf to work showing my web page just how I want it in the pdf(Any other size was not showing right so I kept adjusting the format size until it all fit properly), and the end result is exactly what I want it to look like... EXCEPT even though my aspect ratio is correct for a landscape, it is still using a very large image and the pdf is not standard letter size (Or a4 for that matter), it is the size I set. This makes for a larger pdf than necessary and does not print well unless we adjust it for the printer. I basically want this exact image just converted to a a4 or letter size to make a smaller pdf. If I don't use the size I set though things are cut off.
Anyway to take this pdf that is generated and resize to be an a4 size(Still fitting the image on it). Everything I try is not working, and I feel like I am missing something simple.
const el = document.getElementById("test);
var opt = {
margin: [10, 10, 10, 10],
filename: label,
image: { type: "jpeg", quality: 0.98 },
//pagebreak: { mode: ["avoid-all", "css"], after: ".newPage" },
pagebreak: {
mode: ["css"],
avoid: ["tr"],
// mode: ["legacy"],
after: ".newPage",
before: ".newPrior"
},
/*pagebreak: {
before: ".newPage",
avoid: ["h2", "tr", "h3", "h4", ".field"]
},*/
html2canvas: {
scale: 2,
logging: true,
dpi: 192,
letterRendering: true
},
jsPDF: {
unit: "mm",
format: [463, 600],
orientation: "landscape"
}
};
var doc = html2pdf()
.from(el)
.set(opt)
.toContainer()
.toCanvas()
.toImg()
.toPdf()
.save()
I have been struggling with this a lot as well. In the end I was able to resolve the issue for me. What did the trick for me was setting the width-property in html2canvas. My application has a fixed width, and setting the width of html2canvas to the width of my application, scaled the PDF to fit on an A4 paper.
html2canvas: { width: element_width},
Try adding the above option to see if it works. Try to find out the width of your print area in pixels and replace element_width with that width.
For completeness: I am using Plotly Dash to create web user interfaces. On my interface I include a button that when clicked generates a PDF report of my dashboard. Below I added the code that I used for this, in case anybody is looking for a Dash solution. To get this working in Dash, download html2pdf.bundlemin.js and copy it to the assets/ folder. The PDF file will be downloaded to the browsers default downloads folder (it might give a download prompt, however that wasn't how it worked for me).
from dash import html, clientside_callback
import dash_bootstrap_components as dbc
# Define your Dash app in the regular way
# In the layout define a component that will trigger the download of the
# PDF report. In this example a button will be responsible.
app.layout = html.Div(
id='main_container',
children = [
dbc.Button(
id='button_download_report',
children='Download PDF report',
className='me-1')
])
# Clientside callbacks allow you to directly insert Javascript code in your
# dashboards. There are also other ways, like including your own js files
# in the assets/ directory.
clientside_callback(
'''
function (button_clicked) {
if (button_clicked > 0) {
// Get the element that you want to print. In this example the
// whole dashboard is printed
var element = document.getElementById("main_container")
// create a date-time string to use for the filename
const d = new Date();
var month = (d.getMonth() + 1).toString()
if (month.length == 1) {
month = "0" + month
}
let text = d.getFullYear().toString() + month + d.getDay() + '-' + d.getHours() + d.getMinutes();
// Set the options to be used when printing the PDF
var main_container_width = element.style.width;
var opt = {
margin: 10,
filename: text + '_my-dashboard.pdf',
image: { type: 'jpeg', quality: 0.98 },
html2canvas: { scale: 3, width: main_container_width, dpi: 300 },
jsPDF: { unit: 'mm', format: 'A4', orientation: 'p' },
// Set pagebreaks if you like. It didn't work out well for me.
// pagebreak: { mode: ['avoid-all'] }
};
// Execute the save command.
html2pdf().from(element).set(opt).save();
}
}
''',
Output(component_id='button_download_report', component_property='n_clicks'),
Input(component_id='button_download_report', component_property='n_clicks')
)

How to set the format of text in Korge?

The 2048 Game tutorial shows
text("0", cellSize * 0.5, Colors.WHITE, font) {
setTextBounds(Rectangle(0.0, 0.0, bgScore.width, cellSize - 24.0))
format = format.copy(align = Html.Alignment.MIDDLE_CENTER) // there is an error
centerXOn(bgScore)
alignTopToTopOf(bgScore, 12.0)
}
I use android studio 4.1 and Korge plugin 1.12.2.2. The IDE shows: Unresolved reference.
I change this line to
setFormat(align = TextAlignment.MIDDLE_CENTER)
The error of IDE disappear, but the text don't show either.
How to fix it, and set the text in the middle of the object of bgScore
Thanks a lot
The korge in new version
text("0", cellSize * 0.5, Colors.WHITE, font) {
setTextBounds(Rectangle(0.0, 0.0, bgScore.width, cellSize - 24.0))
// format = format.copy(align = Html.Alignment.MIDDLE_CENTER) // there is an error
alignment = TextAlignment.MIDDLE_CENTER // it works in version korGE 2.0
centerXOn(bgScore)
alignTopToTopOf(bgScore, 12.0)
}

How to add Code128 Barcode image to existing pdf using pdfbox(1.8.12) with barcode4j library?

I am trying to generate the barcode from barcode4j library(code128bean, other barcode beans) and try to add to the existing pdf. The barcode image is getting created locally using the below code.
//Create the barcode bean
Code128Bean code128Bean = new Code128Bean();
final int dpi = 150;
code128Bean.setModuleWidth(UnitConv.in2mm(1.0f / dpi)); //makes the narrow bar
//width exactly one pixel
//bean.setCodeset(2);
code128Bean.doQuietZone(false);
//Open output file
File outputFile = new File("D:/barcode4jcod128.png"); //I dont want to create it
OutputStream code128Stream = new FileOutputStream(outputFile);
try {
//Set up the canvas provider for monochrome PNG output
BitmapCanvasProvider canvas1 = new BitmapCanvasProvider(
code128Stream, "image/x-png", dpi, BufferedImage.TYPE_BYTE_BINARY, false, 0);
//Generate the barcode
code128Bean.generateBarcode(canvas1, "123456");
//Signal end of generation
canvas1.finish();
} finally {
code128Stream.close();
}
My problem is I don't want to create an image and save it locally in filesystem and then add it as image to pdf. I just want to create dynamically i mean just create the barcode image dynamically and add it to the pdf.
How do I set the pagesize (like PDPage.PAGE_SIZE_A4) to the existing PDPages which I retrieved from catalog.getAllPages() method, like (List<PDPage> pages = catalog.getAllPages();)
Can somebody help on this?
Thank you so much for your help Tilman. Here is what i did
public static BufferedImage geBufferedImageForCode128Bean(String barcodeString) {
Code128Bean code128Bean = new Code128Bean();
final int dpi = 150;
code128Bean.setModuleWidth(UnitConv.in2mm(1.0f / dpi)); //makes the narrow bar
code128Bean.doQuietZone(false);
BitmapCanvasProvider canvas1 = new BitmapCanvasProvider(
dpi, BufferedImage.TYPE_BYTE_BINARY, false, 0
);
//Generate the barcode
code128Bean.generateBarcode(canvas1, barcodeString);
return canvas1.getBufferedImage();
}
// main code
PDDocument finalDoc = new PDDocument();
BufferedImage bufferedImage = geBufferedImageForCode128Bean("12345");
PDXObjectImage pdImage = new PDPixelMap(doc, bufferedImage);
PDPageContentStream contentStream = new PDPageContentStream(
finalDoc, pdPage, true, true, true
);
contentStream.drawXObject(pdImage, 100, 600, 50, 20);
contentStream.close();
finalDoc.addPage(pdPage);
finalDoc.save(new File("D:/Test75.pdf"));
The barcode is getting created the but it is created in vertical manner. i would like to see in horizontal manner. Thanks again for your help.
1) add an image to an existing page while keeping the content:
BitmapCanvasProvider canvas1 = new BitmapCanvasProvider(
dpi, BufferedImage.TYPE_BYTE_BINARY, false, 0
);
code128Bean.generateBarcode(canvas1, "123456");
canvas1.finish();
BufferedImage bim = canvas1.getBufferedImage();
PDXObjectImage img = new PDPixelMap(doc, bim);
PDPageContentStream contents = new PDPageContentStream(doc, page, true, true, true);
contents.drawXObject(img, 100, 600, bim.getWidth(), bim.getHeight());
contents.close();
2) set the media box to A4 on an existing page:
page.setMediaBox(PDPage.PAGE_SIZE_A4);

Photoshop Automation of alignment of text layer with image

I have never scripted in photoshop before, so I am wondering if this is possible. The following is currently done manually for over than 300 files. The next time round is for 600 files, therefore I am looking into automating it.
Steps:
Make Image Size to 54pixels Hight and 500px Width -- Found that this is doable.
Align Image Left.
Create a text layer and insert text -- Found that this is doable.
Align Text layer 1px to the right of the image.
Trim empty space.
Would appreciate any help and pointers. Thanks.
This script will get you started: Note that in your request you didn't mention what what the original image was going to be and shrinking it to 500 x 54 is going to stretch it one way or another. Step 2, Align the image left, was omitted as you didn't mention what you are aligning this image to. I suspect you are dealing with a large image and what to shrink it down (as long as it's not smaller than 500 x 54) and work from there. I've also omitted stage 4 as I've hard coded the position of the text to be 1 px from the right hand edge (and it vertically centered with Arial font size 18)
Anhyoo.. you should be able to alter the script to your needs.
// set the source document
srcDoc = app.activeDocument;
//set preference units
var originalRulerPref = app.preferences.rulerUnits;
var originalTypePref = app.preferences.typeUnits;
app.preferences.rulerUnits = Units.POINTS;
app.preferences.typeUnits = TypeUnits.POINTS;
// resize image (ignoring the original aspect ratio)
var w = 500;
var h = 54;
var resizeRes = 72;
var resizeMethod = ResampleMethod.BICUBIC;
srcDoc.resizeImage(w, h, resizeRes, resizeMethod)
//create the text
var textStr = "Some text";
createText("Arial-BoldMT", 18.0, 0,0,0, textStr, w-1, 34)
srcDoc.activeLayer.textItem.justification = Justification.RIGHT
//set preference units back to normal
app.preferences.rulerUnits = originalRulerPref;
app.preferences.typeUnits = originalTypePref;
//trim image to transparent width
app.activeDocument.trim(TrimType.TRANSPARENT, true, true, true, true);
// function CREATE TEXT(typeface, size, R, G, B, text content, text X pos, text Y pos)
// --------------------------------------------------------
function createText(fface, size, colR, colG, colB, content, tX, tY)
{
// Add a new layer in the new document
var artLayerRef = srcDoc.artLayers.add()
// Specify that the layer is a text layer
artLayerRef.kind = LayerKind.TEXT
//This section defines the color of the hello world text
textColor = new SolidColor();
textColor.rgb.red = colR;
textColor.rgb.green = colG;
textColor.rgb.blue = colB;
//Get a reference to the text item so that we can add the text and format it a bit
textItemRef = artLayerRef.textItem
textItemRef.font = fface;
textItemRef.contents = content;
textItemRef.color = textColor;
textItemRef.size = size
textItemRef.position = new Array(tX, tY) //pixels from the left, pixels from the top
}
Everything you listed is doable in a script. I suggest you start by reading 'Adobe Intro To Scripting' in your ExtendScript Toolkit program files directory (e.g. C:\Program Files (x86)\Adobe\Adobe Utilities - CS6\ExtendScript Toolkit CS6\SDK\English)

Imagick - get a thumbnail for each page of a PDF file

I'm trying to get some information from pdf-files that i uploaded via move_uploaded_file().
I need thumbnails of each page to do some color analysis. further i need the width and height of each page in an actual unit of distance (not pixel).
is there a way to do the conversion from pdf to image in imagick not imagemagick. just because I'm using the imagick instace for the color analysis.
now this works for a single image file but not for a multipage pdf.
what to do know...?
/* Read the image */
$im = new Imagick($file);
/* Thumbnail the image */
$im->thumbnailImage(null, 200);
/* Overwrite it */
file_put_contents($file, $im);
/* Gather Info */
$width = $im->getImageWidth();
$height = $im->getImageHeight();
$ratio = $width / $height;
/* Calculate gray */
$pixel_count = 0;
$sum_gray = 0;
for ($row=0;$row<$height;$row++) {
for ($col=0;$col<$width;$col++) {
$pixel = $im->getImagePixelColor($col, $row);
$rgb = $pixel->getColor();
$this_gray = .299*$rgb['r'] + .587*$rgb['g'] + .114*$rgb['b'];
$sum_gray += $this_gray;
$pixel_count++;
}
}
$gray = (1-($sum_gray / $pixel_count) / 256)*100;
and if anybody knows how to get the height and width information, plaes let me know.
thanks for the help!