Change HardMarginX for Print PDF File using PdfiumViewer - c#

I used pdfiumViewer to print a label created by itextshape, i finded this code in stackoverflow, it's work good for A4 paper but for custom paper like my label the problem going to happening. This is code:
public static void PrintPDF(string printer, string paperName, string filename, int copies, bool isduplex = false, bool isHorizontal = false, bool printLabel = false)
{
try
{ // Create the printer settings for our printer
var printerSettings = new PrinterSettings
{
PrinterName = printer,
Copies = (short)copies,
Duplex = Duplex.Simplex,
};
if (isduplex && printerSettings.CanDuplex && isHorizontal)
{
printerSettings.Duplex = Duplex.Horizontal;
}
if (isduplex && printerSettings.CanDuplex && isHorizontal == false)
{
printerSettings.Duplex = Duplex.Vertical;
}
// Create our page settings for the paper size selected
var pageSettings = new PageSettings(printerSettings)
{
};
if (printLabel == true)
{
PaperSize paper = new PaperSize("label", 460, 260);
pageSettings.PaperSize = paper;
pageSettings.Margins = new Margins(0, 0, 0, 0);
}
else
{
foreach (PaperSize paperSize in printerSettings.PaperSizes)
{
if (paperSize.PaperName == paperName)
{
pageSettings.PaperSize = paperSize;
break;
}
}
}
// Now print the PDF document
if (printerSettings.IsValid)
{
using (var document = PdfiumViewer.PdfDocument.Load(filename))
{
using (var printDocument = document.CreatePrintDocument(PdfiumViewer.PdfPrintMode.CutMargin))
{
printDocument.PrintController = new StandardPrintController();
printDocument.OriginAtMargins = true;
printDocument.PrinterSettings = printerSettings;
printDocument.DefaultPageSettings = pageSettings;
printDocument.Print();
}
}
}
}
catch
{
throw;
}
}
The problem is the HardMarginX alway is 20. It is readonly properties so i can not change. So when i print, paper alway margin left some space. So anyway i can do to fix this problem.
Thank for reading

PaperSize paperSize = new PaperSize("Test", 315, 300);
paperSize.RawKind = (int)PaperKind.Custom;
Using This Code

Related

Tesseract self fails and closes

After running for 1 hour, my picture solving application using Teserract crashes:
System.AccessViolationException: 'An attempt to read or write protected memory. This is usually an indication that the other memory is corrupt.'
try
{
IWebElement ttID = driver.FindElement(By.CssSelector("div#root div.captcha__container > img"));
pictureBox1.ImageLocation = ttID.GetAttribute("src");
Thread.Sleep(2000);
var img = new Bitmap(pictureBox1.Image);
var ocr = new TesseractEngine("./tessdata", "eng");
var sonuc = ocr.Process(img);
richTextBox1.Text = sonuc.GetText();
if (infoCheckBox.Checked == true)
{
durum.Text = "otomatik çözme deneniyor...";
Yandexİleri();
}
durum.Text = "otomatik çözme denendi.";
}
catch
{
baslat_kodlari();
}
My suspition is memoty leak, I hope this helps:
try
{
IWebElement ttID = driver.FindElement(By.CssSelector("div#rootdiv.captcha__container > img"));
pictureBox1.ImageLocation = ttID.GetAttribute("src");
Thread.Sleep(2000);
using (var img = new Bitmap(pictureBox1.Image))
{
var ocr = new TesseractEngine("./tessdata", "eng");
var sonuc = ocr.Process(img);
richTextBox1.Text = sonuc.GetText();
if (infoCheckBox.Checked == true)
{
durum.Text = "otomatik çözme deneniyor...";
Yandexİleri();
}
durum.Text = "otomatik çözme denendi.";
}
}
catch
{
baslat_kodlari();
}``

How to choose multiple image from Gallery at one time (tickbox) in Xamarin Android?

Hi have a Xamarin Android project using C#. Currently I am using await CrossMedia.Current.PickPhotoAsync() method to upload image. However, it did not provide a tickbox beside the images for me to select multiple. How can I manage to select multiple images and upload together?
You could implement it by yourself.
1.Add these methods to your MainActivity.cs file
public static int OPENGALLERYCODE = 100;
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
//If we are calling multiple image selection, enter into here and return photos and their filepaths.
if (requestCode == OPENGALLERYCODE && resultCode == Result.Ok)
{
List<string> images = new List<string>();
if (data != null)
{
//Separate all photos and get the path from them all individually.
ClipData clipData = data.ClipData;
if (clipData != null)
{
for (int i = 0; i < clipData.ItemCount; i++)
{
ClipData.Item item = clipData.GetItemAt(i);
Android.Net.Uri uri = item.Uri;
var path = GetRealPathFromURI(uri);
if (path != null)
{
images.Add(path);
}
}
}
else
{
Android.Net.Uri uri = data.Data;
var path = GetRealPathFromURI(uri);
if (path != null)
{
images.Add(path);
}
}
}
}
}
/// <summary>
/// Get the real path for the current image passed.
/// </summary>
public String GetRealPathFromURI(Android.Net.Uri contentURI)
{
try
{
ICursor imageCursor = null;
string fullPathToImage = "";
imageCursor = ContentResolver.Query(contentURI, null, null, null, null);
imageCursor.MoveToFirst();
int idx = imageCursor.GetColumnIndex(MediaStore.Images.ImageColumns.Data);
if (idx != -1)
{
fullPathToImage = imageCursor.GetString(idx);
}
else
{
ICursor cursor = null;
var docID = DocumentsContract.GetDocumentId(contentURI);
var id = docID.Split(':')[1];
var whereSelect = MediaStore.Images.ImageColumns.Id + "=?";
var projections = new string[] { MediaStore.Images.ImageColumns.Data };
cursor = ContentResolver.Query(MediaStore.Images.Media.InternalContentUri, projections, whereSelect, new string[] { id }, null);
if (cursor.Count == 0)
{
cursor = ContentResolver.Query(MediaStore.Images.Media.ExternalContentUri, projections, whereSelect, new string[] { id }, null);
}
var colData = cursor.GetColumnIndexOrThrow(MediaStore.Images.ImageColumns.Data);
cursor.MoveToFirst();
fullPathToImage = cursor.GetString(colData);
}
return fullPathToImage;
}
catch (Exception ex)
{
Toast.MakeText(Xamarin.Forms.Forms.Context, "Unable to get path", ToastLength.Long).Show();
}
return null;
}
2.invoked the following in the specific Activity which you want to open the picker
public void OpenGallery()
{
try
{
var imageIntent = new Intent(Intent.ActionPick);
imageIntent.SetType("image/*");
imageIntent.PutExtra(Intent.ExtraAllowMultiple, true);
imageIntent.SetAction(Intent.ActionGetContent);
this.StartActivityForResult(Intent.CreateChooser(imageIntent, "Select photo"), OPENGALLERYCODE);
Toast.MakeText(this, "Tap and hold to select multiple photos.", ToastLength.Short).Show();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
Toast.MakeText(this, "Error. Can not continue, try again.", ToastLength.Long).Show();
}
}
void ClearFileDirectory()
{
var directory = new Java.IO.File(Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures), ImageHelpers.collectionName).Path.ToString();
if (Directory.Exists(directory))
{
var list = Directory.GetFiles(directory, "*");
if (list.Length > 0)
{
for (int i = 0; i < list.Length; i++)
{
File.Delete(list[i]);
}
}
}
}
//collectionName is the name of the folder in your Android Pictures directory.
public static readonly string collectionName = "TmpPictures";
public string SaveFile(byte[] imageByte, string fileName)
{
var fileDir = new Java.IO.File(Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures), collectionName);
if (!fileDir.Exists())
{
fileDir.Mkdirs();
}
var file = new Java.IO.File(fileDir, fileName);
System.IO.File.WriteAllBytes(file.Path, imageByte);
return file.Path;
}
public string CompressImage(string path)
{
byte[] imageBytes;
//Get the bitmap.
var originalImage = BitmapFactory.DecodeFile(path);
//Set imageSize and imageCompression parameters.
var imageSize = .86;
var imageCompression = 67;
//Resize it and then compress it to Jpeg.
var width = (originalImage.Width * imageSize);
var height = (originalImage.Height * imageSize);
var scaledImage = Bitmap.CreateScaledBitmap(originalImage, (int)width, (int)height, true);
using (MemoryStream ms = new MemoryStream())
{
scaledImage.Compress(Bitmap.CompressFormat.Jpeg, imageCompression, ms);
imageBytes = ms.ToArray();
}
originalImage.Recycle();
originalImage.Dispose();
GC.Collect();
return SaveFile(imageBytes, Guid.NewGuid().ToString());
}

Printing PDF using different printer trays c#

Is there a way to print a PDF and select the paper tray to use programmatically?
I'm open to suggestions such as converting the PDF to a different format and printing from there.
I can print to the correct tray using PaperSource() and PrintDocument() is it possible to convert PDFs into a format that these functions can understand?
Thanks.
Based on getting the paper tray PaperSource from something like here on MSDN, if you don't mind using Ghostscript.NET, this should work for you:
public void PrintPdf(string filePath, string printQueueName, PaperSource paperTray)
{
using (ManualResetEvent done = new ManualResetEvent(false))
using (PrintDocument document = new PrintDocument())
{
document.DocumentName = "My PDF";
document.PrinterSettings.PrinterName = printQueueName;
document.DefaultPageSettings.PaperSize = new PaperSize("Letter", 850, 1100);
document.DefaultPageSettings.PaperSource = paperTray;
document.OriginAtMargins = false;
using (var rasterizer = new GhostscriptRasterizer())
{
var lastInstalledVersion =
GhostscriptVersionInfo.GetLastInstalledVersion(
GhostscriptLicense.GPL | GhostscriptLicense.AFPL,
GhostscriptLicense.GPL);
rasterizer.Open(filePath, lastInstalledVersion, false);
int xDpi = 96, yDpi = 96, pageNumber = 0;
document.PrintPage += (o, p) =>
{
pageNumber++;
p.Graphics.DrawImageUnscaledAndClipped(
rasterizer.GetPage(xDpi, yDpi, pageNumber),
new Rectangle(0, 0, 850, 1100));
p.HasMorePages = pageNumber < rasterizer.PageCount;
};
document.EndPrint += (o, p) =>
{
done.Set();
};
document.Print();
done.WaitOne();
}
}
}

Render a barcode in ASP.NET Web Form

i am trying to show the barcode in asp.net page. already download the zen barcode render with sample code. i tried the sample it is working fine with me. once i try in my code barcode label is showing empty. i checked with sample code and mine i did not find any difference , only data transfer is the different. this is what i tried.
<barcode:BarcodeLabel ID="BarcodeLabel1" runat="server" BarcodeEncoding="Code39NC" LabelVerticalAlign="Bottom" Text="12345"></barcode:BarcodeLabel>
if (!IsPostBack)
{
List<string> symbologyDataSource = new List<string>(
Enum.GetNames(typeof(BarcodeSymbology)));
symbologyDataSource.Remove("Unknown");
barcodeSymbology.DataSource = symbologyDataSource;
barcodeSymbology.DataBind();
}
this is the function
BarcodeSymbology symbology = BarcodeSymbology.Unknown;
if (barcodeSymbology.SelectedIndex != 0)
{
symbology = (BarcodeSymbology)1;
}
symbology = (BarcodeSymbology)1;
string text = hidID.Value.ToString();
string scaleText = "1";
int scale;
if (!int.TryParse(scaleText, out scale))
{
if (symbology == BarcodeSymbology.CodeQr)
{
scale = 3;
}
else
{
scale = 1;
}
}
else if (scale < 1)
{
scale = 1;
}
if (!string.IsNullOrEmpty(text) && symbology != BarcodeSymbology.Unknown)
{
barcodeRender.BarcodeEncoding = symbology;
barcodeRender.Scale = 1;
barcodeRender.Text = text;
}
symbology is set as Code39NC from the dropdown. scale is 1 and text is coming from other form the value is passing as well. still the bacodelable is showing only value not the barcode picture.
Here are two code samples using ZXing to create a (QR) barcode as both an image and as a base64 encoded string. Both of these options can be used with an <img /> tag to embed the barcode in the page.
This is not an ASP.NET control. It is a library that creates barcodes from text.
// First Text to QR Code as an image
public byte[] ToQRAsGif(string content)
{
var barcodeWriter = new BarcodeWriter
{
Format = BarcodeFormat.QR_CODE,
Options = new EncodingOptions
{
Height = this._h,
Width = this._w,
Margin = 2
}
};
using (var bitmap = barcodeWriter.Write(content))
using (var stream = new MemoryStream())
{
bitmap.Save(stream, ImageFormat.Gif);
stream.Position = 0;
return stream.GetBuffer();
}
}
// From Text to QR Code as base64 string
public string ToQRAsBase64String(string content)
{
var barcodeWriter = new BarcodeWriter
{
Format = BarcodeFormat.QR_CODE,
Options = new EncodingOptions
{
Height = _h,
Width = _w,
Margin = 2
}
};
using (var bitmap = barcodeWriter.Write(content))
using (var stream = new MemoryStream())
{
bitmap.Save(stream, ImageFormat.Gif);
return String.Format("data:image/gif;base64,{0}", Convert.ToBase64String(stream.ToArray()));
}
}
Hope this helps! Happy coding.
UPDATE: Here is the link to their product page on codeplex: https://zxingnet.codeplex.com/

Colour appears faded in corrected CMYK image

I am compressing a pdf containing a number of images. The below code I got while browsing for the PDF compression. It works fine for RBG format images but in case of CMYK format the images appears with inverted colours (as a negative). Somehow I was able to convert the inverted colours but the image colour got faded.
Please suggest how should I proceed. Thanks in advance.
{
PdfReader.unethicalreading = true;
string pdfFile = #"C:\TestPdf.pdf";
PdfReader reader = new PdfReader(pdfFile);
long quality = 50L;
int n = reader.XrefSize;
for (int i = 0; i < n; i++)
{
PdfObject obj = reader.GetPdfObject(i);
if (obj == null || !obj.IsStream()) { continue; }
PdfDictionary dict = (PdfDictionary)PdfReader.GetPdfObject(obj);
PdfObject pdfcolorspace = dict.Get(PdfName.COLORSPACE);
PdfName subType = (PdfName)PdfReader.GetPdfObject(dict.Get(PdfName.SUBTYPE));
if (!PdfName.IMAGE.Equals(subType)) { continue; }
PRStream stream = (PRStream)obj;
try
{
PdfImageObject image = new PdfImageObject(stream);
PdfName filter = (PdfName)image.Get(PdfName.FILTER);
if ( PdfName.JBIG2DECODE.Equals(filter) || PdfName.JPXDECODE.Equals(filter) || PdfName.CCITTFAXDECODE.Equals(filter) || PdfName.FLATEDECODE.Equals(filter))
continue;
System.Drawing.Image img = image.GetDrawingImage();
if (img == null) continue;
var ll = image.GetImageBytesType();
int width = img.Width;
int height = img.Height;
using (System.Drawing.Bitmap dotnetImg = new System.Drawing.Bitmap(img))
{
System.Drawing.Imaging.ImageCodecInfo codec = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders()[1];
System.Drawing.Imaging.EncoderParameters eParams = new System.Drawing.Imaging.EncoderParameters(1);
eParams.Param[0] = new System.Drawing.Imaging.EncoderParameter( System.Drawing.Imaging.Encoder.Quality, quality);
using (MemoryStream msImg = new MemoryStream())
{
dotnetImg.Save(msImg, codec, eParams);
msImg.Position = 0;
stream.Clear();
if (pdfcolorspace == PdfName.DEVICECMYK)
{
img.Save(msImg, ImageFormat.Jpeg);
stream.Put(PdfName.COLORSPACE, PdfName.DEVICECMYK);
}
else
{
stream.Put(PdfName.COLORSPACE, PdfName.DEVICERGB);
}
stream.SetData( msImg.ToArray(), true, PdfStream.BEST_COMPRESSION);
stream.Put(PdfName.TYPE, PdfName.XOBJECT);
stream.Put(PdfName.SUBTYPE, PdfName.IMAGE);
stream.Put(PdfName.FILTER, PdfName.DCTDECODE);
stream.Put(PdfName.WIDTH, new PdfNumber(width));
stream.Put(PdfName.HEIGHT, new PdfNumber(height));
stream.Put(PdfName.BITSPERCOMPONENT, new PdfNumber(8));
}
}
}
catch (Exception ex)
{
}
finally
{
reader.RemoveUnusedObjects();
}
}
PdfStamper stamper = new PdfStamper(reader, new FileStream(#"C:\Compress.pdf", FileMode.Create), PdfWriter.VERSION_1_5);
stamper.FormFlattening = false;
stamper.SetFullCompression();
stamper.Close();
reader.Close();
}

Categories

Resources