iTextSharp: Why when adding a image to a pdf page the text font is different? - image

I use Helvetica font and 14 px size for text. The problem is that if a page does not have any image on it the text is very clear, but in a page with at least 1 image the text is getting a little bold. You can see what I mean in images below:
* Without image on page
* With image on page
The correct font is the one that appear in picture #1. How to make all pages have the same font even if the page contains an image or not?
Thanks.
Sample code:
Document document = new Document(PageSize.LETTER);
document.SetMargins(docMargin, docMargin, docMargin, 25);
writer = PdfWriter.GetInstance(document, new FileStream(filename, FileMode.Create));
document.Open();
Font defaultFont = FontFactory.GetFont("Helvetica", 7.8, Font.NORMAL, new Color(75, 75, 75));
document.Add(new Paragraph("Lorem ipsum lorem ipsum lorem ipsum", defaultFont));
document.Add(Chunk.NEWLINE);
Image img = Image.GetInstance("my png image path");
document.Add(img);
document.Close();

I was finally able to reproduce your problem. The first PNG that I tested with which didn't reproduce your problem I created from Photoshop and used the Save For Web command. The second PNG that I tested and was able to reproduce your problem I created from MSPAINT.EXE. I tried various combinations within Save For Web and none of them have the same problem as Paint.
According to this thread from the official iText mailing list it appears to be something about the color profile of the image.
What are you seeing is the impact of newly placed transparency into a
PDF that had not previously contained it, when consideration isn't
given for the blending colorspace of the final output document.
You have an RGB document that upon adding transparency is forced into
CMYK due to lack of explicit blending space. If you were to specify
RGB as your explicit blending space at the same time you added your
transparency, all would be well.
One thing they recommend is setting the following property on your PdfWriter before adding anything:
writer.RgbTransparencyBlending = true;
When I do it I still see a very minor shift but no where near as pronounced as without it.

This isn't an answer, I just need to be able to post code.
I'm unable to reproduce your results but if I were to guess it has something to do with your PDF renderer. You can confirm this by zooming in on the text, does it look the same when zoomed in? If so, that's your renderer trying to apply visual hints to a print document. If not, can you post a simplified version of your code that does this? Does this do this for all images or just one specific one? How are you creating your text, with Paragraphs, Tables, HTML parsing or something else? What version of iTextSharp are you using?
Below is a full working WinForms C# 2010 targeting iTextSharp 5.1.2.0 that creates a two page PDF. The first page has just text and the second page has text followed by an image loaded from the desktop. On my machine, using Adobe Acrobat Pro 9.1.3 I don't see any difference in fonts when I view it on screen.
using System;
using System.IO;
using System.Windows.Forms;
using iTextSharp.text;
using iTextSharp.text.pdf;
namespace WindowsFormsApplication1 {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) {
string pdfFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Test.pdf");
string imgFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Test.png");
using (FileStream fs = new FileStream(pdfFile, FileMode.Create, FileAccess.Write, FileShare.None)) {
using (Document doc = new Document(PageSize.LETTER)) {
using (PdfWriter writer = PdfWriter.GetInstance(doc, fs)) {
doc.Open();
BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED);
iTextSharp.text.Font f = new iTextSharp.text.Font(bf, 14);
doc.NewPage();
doc.Add(new Paragraph("This is a test", f));
doc.NewPage();
doc.Add(new Paragraph("This is a test", f));
iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(imgFile);
img.ScaleAbsolute(100, 100);
doc.Add(img);
doc.Close();
}
}
}
this.Close();
}
}
}

Related

.svg Image in MAUI Blazor

i am trying to set an image in to a razor page in MAUI Blazor.
In MAUI (only), there was the aproach, that you have a .svg image in the folder Resources/Images. MAUI then converts the .svg image in a .png image which you can use in the XAML file. like so:
Now i have the same picture in a MAUI Blazor app and i hoped that i can put my picture in the same way expect that i have to use the HTML style like so:
<img src="one_list2.png">
But this doesn't work at all. I tryed with or witout path, path with slashes, backslashes etc. nothing works.
Trying to put a .png image into the wwwroot folder works. But this isn't the goal. I found it very nice to put a svg image which is then converted into a png depending of its size. This way all pictures would be converted exactly in the perfect size you will need lossless.
Thanks
First, Add the image to Resources\Raw and set it to MauiAsset compilation type
Second, Check the project file to avoid setting the image in the other folder.
In razor component HTML:
<img src="#imageSource">
In the code part:
private string? imageSource;
protected override async Task OnInitializedAsync()
{
try
{
using var stream =
await FileSystem.OpenAppPackageFileAsync("testimage.png");
using var reader = new StreamReader(stream);
byte[] result;
using (var streamReader = new MemoryStream())
{
stream.CopyTo(streamReader);
result = streamReader.ToArray();
}
imageSource = Convert.ToBase64String(result);
imageSource = string.Format("data:image/png;base64,{0}", imageSource);
}
catch (Exception ex)
{
//error
}
}
More information you can refer to ASP.NET Core Blazor Hybrid static files.

How to get SetMultiline(true) to honor wrapping of text

I'm attempting to add form fields to an existing PDF in a .NET 7.0.0 app using iText7 7.2.4 on Mac and I cannot get multiline text fields to honor wrapping without doing a weird hack.
The following code illustrates the issue:
using iText.Forms;
using iText.Forms.Fields;
using iText.IO.Font.Constants;
using iText.Kernel.Colors;
using iText.Kernel.Font;
using iText.Kernel.Geom;
using iText.Kernel.Pdf;
// Create a new PDF document
PdfDocument pdf = new PdfDocument(new PdfWriter("my_document.pdf"));
// Create a page and add it to the document
PdfPage page = pdf.AddNewPage();
// Create an AcroForm and add it to the document
PdfAcroForm form = PdfAcroForm.GetAcroForm(pdf, true);
// Create a multiline text field that should wrap but does not.
PdfTextFormField nonWrapping = PdfFormField.CreateText
(pdf,
new Rectangle(25, 727, 100, 100),
"multiline-field-without-wrapping",
String.Concat(Enumerable.Repeat("Hello World ", 10)),
PdfFontFactory.CreateFont(StandardFonts.HELVETICA),
9.0F);
nonWrapping.SetMultiline(true);
form.AddField(nonWrapping);
// Create a multiline text field that DOES wrap but
// only because we set a background color.
PdfTextFormField wrapping = PdfFormField.CreateText
(pdf,
new Rectangle(150, 727, 100, 100),
"multiline-field-with-wrapping",
String.Concat(Enumerable.Repeat("Hello World ", 10)),
PdfFontFactory.CreateFont(StandardFonts.HELVETICA),
9.0F);
wrapping.SetMultiline(true);
wrapping.SetBackgroundColor(new DeviceRgb(0.9F, 0.9F, 0.99F));
form.AddField(wrapping);
// Close the document
pdf.Close();
It will result in a PDF that looks like this in Preview:
The only way I can get wrapping to work is by including background color. I don't want to do this but it's the only thing that works.
If I could set the opacity of the background color, that might also be acceptable but so far, I've been unable to find anything in the code or docs that would support this.

iText extract text from rotated page

I'm trying to extract text from a rotated PDF page: the page has "/Rotate 90" instruction inside. This mean page is rotated when displayed, but it seems not be rotated when extracting text with PdfTextExtractor and LocationTextExtractionStrategy.
I followed example by Mr. Lowagie on
this link
I tryed to rotate area instead of page, but it seem to extract whole text block as one piece instead the exact selected area.
I'm using iText 5.5.12 with Java 1.8
How can I rotate the page for extraction?
Update
The code I use is like this:
PdfReader reader = null;
try {
reader = new PdfReader("C:\\Temp\\rotated.pdf");
Rectangle rect = new Rectangle(480, 484, 576, 525);
final Rectangle pageRect = reader.getPageSize(1);
RenderFilter regionFilter = new RegionTextRenderFilter(rect);
TextExtractionStrategy strategy = new FilteredTextRenderListener(new LocationTextExtractionStrategy(),
regionFilter);
System.out.println(">>" + PdfTextExtractor.getTextFromPage(reader, 1, strategy).trim());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null)
reader.close();
}
I can't find a way to upload here an example PDF. I put this image taken from Gimp with selected area. Pdf was created with LibreOffice export function and then manually edited to add /Rotate command.
Given coordinates consider zero point on lower-right corner.
Program output is empty string.

How to get Resized/Thumbnail Image : UWP

Currently I was working on a UWP application. I captured the ink strokes into an image. Now the same image need to display as a preview. So the original image need to re-size to shorter size or thumbnail need to be generated.
I tried with using the larger image directly as a source to shorter sized image canvas --> not working (visible image quality degrade)
I also used Transcode of image programatically --> same result as above
I test with the same image. Re-sized the same image using paint, and there interestingly the quality of the re-sized image remains good.
Please help me to solve the issue I faced.
I not sure, need to see some code, but could be how you are saving the image? Here an example:
try
{
Windows.Storage.Pickers.FileSavePicker save = new Windows.Storage.Pickers.FileSavePicker();
save.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Desktop;
save.DefaultFileExtension = “.png”;
save.FileTypeChoices.Add(“PNG”, new string[] { “.png” });
StorageFile filesave = await save.PickSaveFileAsync();
using (IOutputStream fileStream = await filesave.OpenAsync(FileAccessMode.ReadWrite))
{
if (fileStream != null)
{
await m_InkManager.SaveAsync(fileStream);
}
}
}
catch (Exception ex)
{
var dialog = new MessageDialog(ex.Message);
dialog.ShowAsync();
}
I will post a great tutorial of Can Bilgin that explain perfectly all about inking.
Drawing / Inking API in WinRT (C#) – I
Drawing / Inking API in WinRT (C#) – II
Drawing / Inking API in WinRT (C#) – III

Save WF 4 workflow as Image

The problem is that I am opening workflow designer dynamically from one shell application and I don't have reference to Canvas. I am able to save the WF4 as image but the image is not getting saved properly and contains left & top margins. I followed many articles to get it working but no success. I referred to following article as well.
Saving a canvas to png C# wpf
I am using the below function. I don't have any reference to canvas.
private BitmapFrame CreateWorkflowImage()
{
const double DPI = 96.0;
Visual areaToSave = ((DesignerView)VisualTreeHelper.GetChild(this.wd.View,
0)).RootDesigner;
Rect bounds = VisualTreeHelper.GetDescendantBounds(areaToSave);
RenderTargetBitmap bitmap = new RenderTargetBitmap((int)bounds.Width,
(int)bounds.Height, DPI, DPI, PixelFormats.Default);
bitmap.Render(areaToSave);
return BitmapFrame.Create(bitmap);
}
Please help on this.
I am able to resolve the issue by referring to again the following link
Saving a canvas to png C# wpf
I got the reference to canvas by using following code
Visual canvas= ((DesignerView)VisualTreeHelper.GetChild(this.WorkflowDesigner1.View, 0)).RootDesigner;
This has resolved the border/margin issue.
Please have a look here: http://blogs.msdn.com/b/flow/archive/2011/08/16/how-to-save-wf4-workflow-definition-to-image-using-code.aspx
let’s look at how to generate an image of the workflow definition using the standard mechanism of WPF. After all, workflow designer canvas is a WPF control.
BitmapFrame CreateWorkflowDefinitionImage()
{
const double DPI = 96.0;
// this is the designer area we want to save
Visual areaToSave = ((DesignerView)VisualTreeHelper.GetChild(
this.workflowDesigner.View, 0)).RootDesigner;
// get the size of the targeting area
Rect size = VisualTreeHelper.GetDescendantBounds(areaToSave);
RenderTargetBitmap bitmap = new RenderTargetBitmap((int)size.Width, (int)size.Height,
DPI, DPI, PixelFormats.Pbgra32);
bitmap.Render(areaToSave);
return BitmapFrame.Create(bitmap);
}
The above C# method is very straightforward. Just get the workflow diagram part of the workflow designer and create an in-memory image of it using some WPF API. The next thing is simple: create a file and save the image.
void SaveImageToFile(string fileName, BitmapFrame image)
{
using (FileStream fs = new FileStream(fileName, FileMode.Create))
{
BitmapEncoder encoder = new JpegBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(image));
encoder.Save(fs);
fs.Close();
}
}
At last, let’s try to invoke the above 2 methods in the OnInitialized() method to hook it up and then close the application.
protected override void OnInitialized(EventArgs e)
{
// ...
this.SaveImageToFile("test.jpg", this.CreateWorkflowDefinitionImage());
Application.Current.Shutdown();
}

Resources