We have .net Web API to generate pdf based on certain parameters, this pdf will have images in .eps and .ai (vector images). We are using itext7 html2pdf and passing html as string to the method ConvertToPdf but it's not able to recognize those vector images.
Need help to add vector image in pdf to retain the image quality in pdf and the file size should not increase more than 2MB.
Please find code snippet:
public string GenerateHtmlToPdf(string html , string fileName)
{
//generate pdf from html using iText7
try
{
string filePath = WebConfigurationManager.AppSettings["filePath"];
FileStream finalPdfPath = new FileStream(filePath + "\\" + fileName + ".pdf", FileMode.Create);
string finalPath = filePath + fileName + ".pdf";
PdfFontFactory.RegisterDirectory(FONTDIR);
var NewTransportBold = PdfFontFactory.CreateRegisteredFont("NewTransport-Bold", PdfEncodings.IDENTITY_H);
var NewTransportNormal = PdfFontFactory.CreateRegisteredFont("NewTransport-Regular", PdfEncodings.IDENTITY_H);
var NewTransportLight = PdfFontFactory.CreateRegisteredFont("NewTransport-Light", PdfEncodings.IDENTITY_H);
HtmlConverter.ConvertToPdf(html, finalPdfPath);
return finalPath;
}
catch (IOException ex)
{
var exists = File.Exists("File already exist on desktop");
return "file exist";
}
//end
}
As for pdfs, it is not possible to add svg formats.Hence the svg image would have to be added to the document where the html was set separately.For this a NuGet package named Svg is used.
public void AddSVG(string resourceLocator, float x, float y, int page, int scalePresent = 100)
{
var webClient = new WebClient();
MemoryStream memoryFile = new MemoryStream(webClient.DownloadData(resourceLocator));
SvgDocument memorySVGFile = SvgDocument.Open<SvgDocument>(memoryFile);//get the img as svg doc
var imgconv = memorySVGFile.Draw(3000, 3000);
MemoryStream imgStream = new MemoryStream();
imgconv.Save(imgStream, ImageFormat.Png);//convert svg doc in to a png and save in a mem stream
Image img = new Image(ImageDataFactory.Create(imgStream.ToArray())); //create itext image object from byte array
img.SetFixedPosition(page,x, y, 550);
doc.Add(img);
memoryFile.Close();
}
here the string resourceLocator is the path to the svg. And "doc." is the pdf document where the html was converter to a pdf document.
Related
I'm trying to use custom fonts for my itext7 to allow my pdf to write Arabic texts. what I did is the following:
var path2 = global::Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
filePath = System.IO.Path.Combine(path2.ToString(), "myfile3.pdf");
stream = new FileStream(filePath, FileMode.Create);
iText.Layout.Element.Table table = new iText.Layout.Element.Table(3, false);
table.SetWidth(400).SetFixedLayout();
string[] sources = new string[] { "يوم","شهر 2020" };
PdfWriter writer2 = new PdfWriter(stream);
PdfDocument pdfDocument = new PdfDocument(writer2);
Document document2 = new Document(pdfDocument);
PdfFont arab= PdfFontFactory.CreateFont("NotoNaskhArabic-Regular.ttf");
document2.SetFont(arab);
foreach (string source in sources)
{
Paragraph paragraph = new Paragraph();
Bidi bidi = new Bidi(source, Bidi.DirectionDefaultLeftToRight);
if (bidi.BaseLevel != 0)
{
paragraph.SetTextAlignment(iText.Layout.Properties.TextAlignment.RIGHT);
}
paragraph.Add(source);
table.AddCell(new Cell(1,1).SetTextAlignment(iText.Layout.Properties.TextAlignment.CENTER).Add(paragraph));
}
document2.Add(table);
document2.Close();
I tried different paths for my font. I put it in my resources folder, in my assets, tried to reach it from C:\Windows\Fonts\ARIAL.TTF when I tried using arial font, but all of those didn't work, I don't get it, what should my path be so I won't get this exception: System.IO.IOException: path to ttf file not found as file or resource.'
Once you have your file in assets, you could use AssetManager to read the bytes from the font.Then create the font by the bytes.
You could refer to this and convert it to C# code.
This is my code:
File pdfFile = new File(pdfFileLocation);
PDDocument doc = PDDocument.load(pdfFile);
PDFRenderer renderer = new PDFRenderer(doc);
BufferedImage image = renderer.renderImageWithDPI(0, 240);
ImageIO.write(image, "PNG", new File("test.png"));
doc.close();
but the png file have no signature image.
How should I fix this problem?
I am trying to add watermark on pdf file using PdfSharp, I tried from this link
http://www.pdfsharp.net/wiki/Watermark-sample.ashx
but am not able to get how to get the existing pdf file page object and how to watermark on that page.
Help?
Basically, the samples are only snippets. You can download the source and with that you get a bunch of samples, including this watermark example.
The following comes from PDFSharp-MigraDocFoundation-1_32/PDFsharp/samples/Samples C#/Based on GDI+/Watermark/Program.cs
Quite simple, really ... I am only showing the code up to the for loop that goes over each page. You should have a look at the full file.
[...]
const string watermark = "PDFsharp";
const int emSize = 150;
// Get a fresh copy of the sample PDF file
const string filename = "Portable Document Format.pdf";
File.Copy(Path.Combine("../../../../../PDFs/", filename),
Path.Combine(Directory.GetCurrentDirectory(), filename), true);
// Create the font for drawing the watermark
XFont font = new XFont("Times New Roman", emSize, XFontStyle.BoldItalic);
// Open an existing document for editing and loop through its pages
PdfDocument document = PdfReader.Open(filename);
// Set version to PDF 1.4 (Acrobat 5) because we use transparency.
if (document.Version < 14)
document.Version = 14;
for (int idx = 0; idx < document.Pages.Count; idx++)
{
//if (idx == 1) break;
PdfPage page = document.Pages[idx];
[...]
I have created a docX using the docX library and have added an image in the header. However when I convert the docX to PDF using the Spire.doc library, the image is lost. Any idea why? Below is my code:
var doc = DocX.Create(fileName);
string url = #"C:\Users\Desktop\Capture.JPG";
Novacode.Image img = doc.AddImage(url);
Picture pic = img.CreatePicture();
doc.AddHeaders();
Header header_default = doc.Headers.odd;
Paragraph p1 = header_default.InsertParagraph();
p1.Append(headerText).Bold().Color(System.Drawing.Color.LightGray).FontSize(20);
p1.AppendPicture(pic);
doc.Save();
Document docS = new Document();
docS.LoadFromFile(fileName);
string pdfPath = #"C:\Users\Documents\toPDF.PDF";
docS.SaveToFile(pdfPath, FileFormat.PDF);
As you already use Spire.Doc in your code, why not use spire to create header in Word directly and then save the file to PDF file format. I tried following code and it works fine.
using Spire.Doc;
using System.Drawing;
using Spire.Doc.Documents;
namespace Doc2Pdf
{
class Program
{
static void Main(string[] args)
{
Document doc = new Document();
Section section = doc.AddSection();
HeaderFooter header = section.HeadersFooters.Header;
Paragraph p1 = header.AddParagraph();
Image image = Image.FromFile("pic.png");
p1.AppendPicture(image);
doc.SaveToFile("Header.pdf", FileFormat.PDF);
}
}
}
I generated a pdf using PDFBox which is then sent to the front-end. When I print / save this pdf in Chrome / Firefox, it looks good. However, when I try to do the same using Safari, the pdf is magnified.
Not sure if this is a browser issue or whether it has something to do with Safari not able to read the pdf properly. Any ideas?
This is the pdf generated from Chrome, and this is the one from Safari (I've redacted few details).
This is my code:
PDXObjectImage blankImg = (PDXObjectImage) object;
if(blankImg.getHeight() > 460){
BufferedImage img = ImageIO.read(new ByteArrayInputStream(shippingLabel));
BufferedImage resizedImage = Scalr.resize(img, Scalr.Method.BALANCED, Scalr.Mode.FIT_EXACT, img.getWidth(), img.getHeight());
// Convert images to jpg format
BufferedImage jpegImage = new BufferedImage(resizedImage.getWidth(),resizedImage.getHeight(), BufferedImage.TYPE_INT_RGB);
jpegImage.createGraphics().drawImage(resizedImage, 0, 0, Color.WHITE, null);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(jpegImage, "jpg", baos);
// Replace empty image in template with the image generated from shipping label byte array
PDXObjectImage carrierLabel = new PDJpeg(doc, new ByteArrayInputStream(baos.toByteArray()));
blankImg.getCOSStream().replaceWithStream(carrierLabel.getCOSStream());
break;
}
PDStream updatedStream = new PDStream(doc);
OutputStream out = updatedStream.createOutputStream();
ContentStreamWriter tokenWriter = new ContentStreamWriter(out);
tokenWriter.writeTokens(tokens);
page.setContents(updatedStream);
// Convert PDDoc to byte[]
ByteArrayOutputStream outUpdated = new ByteArrayOutputStream();
doc.save(outUpdated);
return outUpdated.toByteArray();
This is what I'm doing. I have a pdf with a blank image. I read this image, and replace this with another existing image which is available as byte array, and finally return the updated pdf as a byte array as ResponseEntity from Spring boot server running in the backend.
Thanks.