Why I am unable to change the QR Code's size in iText7? - itext7

How to change QR Code size?
using (iText.Kernel.Pdf.PdfReader _pdf_reader =
new iText.Kernel.Pdf.PdfReader("tmp/example.pdf"))
{
using (iText.Kernel.Pdf.PdfDocument pdfDoc = new iText.Kernel.Pdf.PdfDocument(_pdf_reader, new iText.Kernel.Pdf.PdfWriter("tmp/output.pdf").SetSmartMode(true)))
{
BarcodeQRCode qrc = new BarcodeQRCode("https://google.com");
PdfFormXObject xObject = qrc.CreateFormXObject(ColorConstants.BLACK, pdfDoc);
float _w = pdfDoc.GetPage(1).GetPageSize().GetWidth();
float _h = pdfDoc.GetPage(1).GetPageSize().GetHeight();
PdfCanvas canvas = new PdfCanvas(pdfDoc.GetPage(1));
canvas.SaveState();
canvas.SetFillColor(ColorConstants.LIGHT_GRAY);
//canvas.Rectangle(_w - 90, _h - 90, 100, 100);
canvas.Fill();
canvas.RestoreState();
canvas.AddXObject(xObject, _w - qrc.GetBarcodeSize().GetWidth(), _h - qrc.GetBarcodeSize().GetHeight());
}
}
I try:
qrc.GetBarcodeSize().GetHeight();
qrc.GetBarcodeSize().GetWidth();
it returns 33
I try to set Height & Width to 100 like below:
qrc.GetBarcodeSize().SetHeight(100);
qrc.GetBarcodeSize().SetWidth(100);
and then check the size again, but it keeps returning 33, is it a bug? or Did I miss something?
please help
thanks
Don

I try to set Height & Width to 100 like below:
Actually, you can`t change the QrCode side this way.
In fact, QRcode is an n*n grid where n depends on some parameters as a QR code version and the error correction level.
When generating, iText uses the smallest version that can fit the content. This is version 4 (33*33) in your case.
The easiest way to change the size of QrCode in a document is by using the version of the createFormXObject method which accepts the moduleSide parameter.
float moduleSize = 100/qrc.GetBarcodeSize().GetHeight();
qrc.createFormXObject(foreground, moduleSize, document)
Module size here is size of the barcode`s grid cell (1 by default).

iTxt 7 Qrcode size effected by three parameter in hints, example example for your reference.
//C# code
//Prepare all necessary properties to create the qrcode
IDictionary<EncodeHintType, Object> hints = new Dictionary<EncodeHintType, object>();
//default character set (ISO-8859-1)
hints[EncodeHintType.CHARACTER_SET] = "UTF-8";
//Qrcode Error correction level L,M,Q,H
//default ErrorCorrectionLevel.L
hints[EncodeHintType.ERROR_CORRECTION] = ErrorCorrectionLevel.L;
//Qrcode minimal version level
//default 4
hints[EncodeHintType.MIN_VERSION_NR] = 6;
string code = "Qrcode content here";
BarcodeQRCode qrcode = new BarcodeQRCode(code, hints);

Related

Canvas resize photoshop script

Would it be possible to write a script to resize each image to the closest round number (for example if the original image is 791x1265px then it could be resized to 800x1300px)
Thanks!
Pretty Easy and small script can do it :) Enjoy
Note : You have two choices for script; before running script either use static base value (default) or if you want to add prompt on each run then uncomment below line of var base and comment the var base line :) Hope that is what you were looking :)
//get Original Ruler Units;
var origRuler = app.preferences.rulerUnits;
app.preferences.rulerUnits = Units.PIXELS;
//get Active document scales
var origWidth = app.activeDocument.width;
var origHeight = app.activeDocument.height;
//define base
var base = 100; //change your base like 10;100 etc; use below code to make a prompt on each run;
//var base = prompt("Enter Your Base number",""); //use this code if you want prompt for each run . uncomment by rermoving first two "//"
//magical Mathematics XD
var roundWidth = Math.ceil(origWidth / base) * base;
var roundHeight = Math.ceil(origHeight / base) * base;
//resize canvas
app.activeDocument.resizeCanvas (roundWidth, roundHeight);
//Restores Original Ruler Units;
app.preferences.rulerUnits = origRuler;
Edit: Updated script to avoid ruler units conflicts and changed Math.round to Math.ceil as per #Sergey Suggestion!

Create Images with watermark in extbase

I have a Model that stores a FileReference. And now I want to create an Image with a Watermark in the Extbase Controller. Does anybody know where I have to look for? I only found solutions with typoscript.
I choosed the TypoScript way and it worked pretty well.
Fluid:
<f:cObject typoscriptObjectPath="lib.tx_myext.watermarkedImage" data="{imageUid:'{image.uid}',copyright:'{image.copyright}')}'}"/>
TypoScript:
lib.tx_myext.watermarkedImage = IMAGE
lib.tx_myext.watermarkedImage {
file = GIFBUILDER
file {
XY = [10.w],[10.h]
format = jpg
10 = IMAGE
10 {
file {
import.field = imageUid
treatIdAsReference = 1
width = 1162
height = 580c
}
}
20 = BOX
20 {
color = #FFFFFF
opacity = 70
dimensions = [10.w]-[30.w]-10,[10.h]-20,[30.w]+20,[30.h]+20
}
30 = TEXT
30 {
text.data = field:copyright
fontSize = 15
fontColor = #000000
fontFile = path/to/my/font.ttf
offset = [10.w]-[30.w]-5,[10.h]-5
}
}
}
The result is an image with a white box and the copyright text on it at the right bottom corner.
I think the easiest way will be to use a typoscript solution. This must not be as pure typoscript, but the datastructure of the typoscript might be needed as parameter to the core functions of the GifBuilder class. TYPO3 7.6 API
The GifBuilder class is inherited from the class GraphicalFunctions which can be used also, as there are only a few additions and the main functionality is here.
The last problem are the examples in the net according this task: they are pibased and all of them end up in something like
$img = $this->cObj->IMAGE($typoScriptArray);
in modern (namespaced) notation using current API this would be:
$gifCreator = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\TYPO3\CMS\Core\Imaging\GifBuilder::class);
$gifCreator->init();
$theImage='';
if ($GLOBALS['TYPO3_CONF_VARS']['GFX']['gdlib']) {
$gifCreator->start($fileArray, $typoScriptArray);
$theImage = $gifCreator->gifBuild();
}

How can I get my PdfPTable's border and background color to display (iTextSharp)?

As you can see, I've got a table which sports borders and a background color (Section 1):
...but section 3 lacks these sartorial refinements, and I don't know why.
Here is the pertinent code for section 1 (which displays as it should):
PdfPTable tblHeadings = new PdfPTable(3);
tblHeadings.WidthPercentage = 100;
tblHeadings.SpacingBefore = 10f;
float[] headingRowWidths = new float[] { 550f, 50f, 400f };
tblHeadings.SetWidths(headingRowWidths);
tblHeadings.HorizontalAlignment = Element.ALIGN_LEFT;
Phrase phrasesec1Heading = new Phrase("Section 1: Payment Information", timesRoman9BoldFont);
PdfPCell cellSec1Heading GetCellForBorderedTable(phrasesec1Heading, Element.ALIGN_LEFT, ucscgold);
tblHeadings.AddCell(cellSec1Heading);
. . .
doc.Add(tblHeadings);
...and here for section 3 (which doesn't display as it should):
// Section 3
PdfPTable tblSection3 = new PdfPTable(1);
tblSection3.WidthPercentage = 100;
tblSection3.SpacingBefore = 10f;
//tblSection3.HorizontalAlignment = Element.ALIGN_LEFT;
Chunk sec3PayeeStatus = new Chunk("Section 3: Payee Status", timesRoman9BoldFont);
Chunk requiredFields = new Chunk(" * Required Fields", timesRoman9BoldRedFont);
Paragraph parSection3 = new Paragraph();
parSection3.Add(sec3PayeeStatus);
parSection3.Add(requiredFields);
//Phrase phrasesec1Heading = new Phrase("Section 1: Payment Information", timesRoman9BoldFont);
PdfPCell cellSec3Heading = GetCellForBorderedTable(parSection3, Element.ALIGN_LEFT, ucscgold);
tblSection3.AddCell(cellSec3Heading);
doc.Add(parSection3);
What am I missing or forgetting? The difference in the table creation and setup is in the number of cells/columns, and related declaration (float array) and property (setWidths()). The code adding to the PdfPCell differs in that a Phrase
is used for Section 1 (which displays as I want it to), and a Paragraph is used for section 3 (which doesn't), but I tried that:
// try using a Phrase instead of a Paragraph
Chunk sec3PayeeStatus = new Chunk("Section 3 PayeeStatus",
timesRoman9BoldFont);
Chunk requiredFields = new Chunk(" * Require Fields",
timesRoman9BoldRedFont);
Phrase phraseSection3 = new Phrase();
phraseSection3.Add(sec3PayeeStatus);
phraseSection3.Add(requiredFields);
PdfPCell cellSec3Heading GetCellForBorderedTable(phraseSection3,
Element.ALIGN_LEFT, ucscgold);
tblSection3.AddCell(cellSec3Heading);
doc.Add(phraseSection3);
...but that did no better, in fact was a little worse, because the "SpacingBefore" didn't seem to "take"
Finally (so far), I tried using Phrases instead of Chunks, like so:
Phrase sec3PayeeStatus = new Phrase("Section 3: Payee Status", timesRoman9BoldFont);
Phrase requiredFields = new Phrase(" * Required Fields", timesRoman9BoldRedFont);
Paragraph parSection3 = new Paragraph();
parSection3.Add(sec3PayeeStatus);
parSection3.Add(requiredFields);
PdfPCell cellSec3Heading = GetCellForBorderedTable(parSection3, Element.ALIGN_LEFT, ucscgold);
tblSection3.AddCell(cellSec3Heading);
doc.Add(parSection3);
...but that is no better, worse, or different than the first attempt (at least I get the vertical space back, though, separating sections 2 and 3).
What do I have to do to display the cell borders and background color?
UPDATE
Here's GetCellForBorderedTable():
private static PdfPCell GetCellForBorderedTable(Phrase phrase, int align, BaseColor color)
{
PdfPCell cell = new PdfPCell(phrase);
cell.HorizontalAlignment = align;
cell.PaddingBottom = 2f;
cell.PaddingTop = 0f;
cell.BackgroundColor = color;
cell.VerticalAlignment = PdfPCell.ALIGN_CENTER;
return cell;
}
The problem was (not "visible" to me until I compared the code in a code comparison utility, namely KDiff3) that I was adding the Paragraph, not the table, to the doc:
doc.Add(parSection3);
Now that I've changed that to:
doc.Add(tblSection3);
...it works.

Win7: Set Custom Text Size changes position of button's image

Good day all! I have a very tricky for me question.
In my application I have button with image inside. All properties of this button:
Me.cmdSelectAll.BackColor = System.Drawing.SystemColors.Control
Me.cmdSelectAll.Image = CType(resources.GetObject("cmdSelectAll.BackgroundImage"), System.Drawing.Image)
Me.cmdSelectAll.ImageAlign = Drawing.ContentAlignment.BottomRight
Me.cmdSelectAll.Cursor = System.Windows.Forms.Cursors.Default
Me.cmdSelectAll.Font = New System.Drawing.Font("Arial", 8.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.cmdSelectAll.ForeColor = System.Drawing.SystemColors.ControlText
Me.cmdSelectAll.Location = New System.Drawing.Point(0, 282)
Me.cmdSelectAll.Name = "cmdSelectAll"
Me.cmdSelectAll.Padding = New System.Windows.Forms.Padding(0, 0, 0, 0)
Me.cmdSelectAll.RightToLeft = System.Windows.Forms.RightToLeft.No
Me.cmdSelectAll.Size = New System.Drawing.Size(22, 22)
Me.cmdSelectAll.TabIndex = 11
Me.cmdSelectAll.TabStop = False
Me.ToolTip1.SetToolTip(Me.cmdSelectAll, "Select All Channels")
Me.cmdSelectAll.UseVisualStyleBackColor = False
When I run it with default text size of win7, the image appears in the center, it's all ok. But when I set some custom value of text size (115%) my image suddenly goes more right and down. It occurs with all of my button's images. Could you please answer me why does this happen and how can i fix this issue? Thanks

Rendering smallest possible image size with MVC3 vs Webforms Library

I am in the process of moving a webforms app to MVC3. Ironically enough, everything is cool beans except one thing - images are served from a handler, specifically the Microsoft Generated Image Handler. It works really well - on average a 450kb photo gets output at roughly 20kb.
The actual photo on disk weighs in at 417kb, so i am getting a great reduction.
Moving over to MVC3 i would like to drop the handler and use a controller action. However i seem to be unable to achieve the same kind of file size reduction when rendering the image. I walked through the source and took an exact copy of their image transform code yet i am only achieving 230~kb, which is still a lot bigger than what the ms handler is outputting - 16kb.
You can see an example of both the controller and the handler here
I have walked through the handler source code and cannot see anything that is compressing the image further. If you examine both images you can see a difference - the handler rendered image is less clear, more grainy looking, but still what i would consider satisfactory for my needs.
Can anyone give me any pointers here? is output compression somehow being used? or am i overlooking something very obvious?
The code below is used in my home controller to render the image, and is an exact copy of the FitImage method in the Image Transform class that the handler uses ...
public ActionResult MvcImage()
{
var file = Server.MapPath("~/Content/test.jpg");
var img = System.Drawing.Image.FromFile(file);
var sizedImg = MsScale(img);
var newFile = Server.MapPath("~/App_Data/test.jpg");
if (System.IO.File.Exists(newFile))
{
System.IO.File.Delete(newFile);
}
sizedImg.Save(newFile);
return File(newFile, "image/jpeg");
}
private Image MsScale(Image img)
{
var scaled_height = 267;
var scaled_width = 400;
int resizeWidth = 400;
int resizeHeight = 267;
if (img.Height == 0)
{
resizeWidth = img.Width;
resizeHeight = scaled_height;
}
else if (img.Width == 0)
{
resizeWidth = scaled_width;
resizeHeight = img.Height;
}
else
{
if (((float)img.Width / (float)img.Width < img.Height / (float)img.Height))
{
resizeWidth = img.Width;
resizeHeight = scaled_height;
}
else
{
resizeWidth = scaled_width;
resizeHeight = img.Height;
}
}
Bitmap newimage = new Bitmap(resizeWidth, resizeHeight);
Graphics gra = Graphics.FromImage(newimage);
SetupGraphics(gra);
gra.DrawImage(img, 0, 0, resizeWidth, resizeHeight);
return newimage;
}
private void SetupGraphics(Graphics graphics)
{
graphics.CompositingMode = CompositingMode.SourceCopy;
graphics.CompositingQuality = CompositingQuality.HighSpeed;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.SmoothingMode = SmoothingMode.HighSpeed;
}
If you don't set the quality on the encoder, it uses 100 by default. You'll never get a good size reduction by using 100 due to the way image formats like JPEG work. I've got a VB.net code example of how to set the quality parameter that you should be able to adapt.
80L here is the quality setting. 80 still gives you a fairly high quality image, but at DRASTIC size reduction over 100.
Dim graphic As System.Drawing.Graphics = System.Drawing.Graphics.FromImage(newImage)
graphic.InterpolationMode = Drawing.Drawing2D.InterpolationMode.HighQualityBicubic
graphic.SmoothingMode = Drawing.Drawing2D.SmoothingMode.HighQuality
graphic.PixelOffsetMode = Drawing.Drawing2D.PixelOffsetMode.HighQuality
graphic.CompositingQuality = Drawing.Drawing2D.CompositingQuality.HighQuality
graphic.DrawImage(sourceImage, 0, 0, width, height)
' now encode and send the new image
' This is the important part
Dim info() As Drawing.Imaging.ImageCodecInfo = Drawing.Imaging.ImageCodecInfo.GetImageEncoders()
Dim encoderParameters As New Drawing.Imaging.EncoderParameters(1)
encoderParameters.Param(0) = New Drawing.Imaging.EncoderParameter(Drawing.Imaging.Encoder.Quality, 80L)
ms = New System.IO.MemoryStream
newImage.Save(ms, info(1), encoderParameters)
When you save or otherwise write the image after setting the encoder parameters, it'll output it using the JPEG encoder (in this case) set to quality 80. That will get you the size savings you're looking for.
I believe it's defaulting to PNG format also, although Tridus' solution solves that also.
However, I highly suggest using this MVC-friendly library instead, as it avoids all the image resizing pitfalls and doesn't leak memory. It's very lightweight, free, and fully supported.

Resources