Replace Image in PDF with another Image pdf box - image

How to replace Image in PDF with another Image pdf box. How to do that?
I want to change VisualSignature on the pdf with another image.
I get Visual Apereance like that:
PDDocument doc= PDDocument.load(new FileInputStream("c:\\temp\\template.pdf"));
File dir= new File("c:\\temp\\");
Iterator<Entry<COSObjectKey, Long>> xrefEntriesIt =
doc.getDocument().getXrefTable().entrySet().iterator();
while( xrefEntriesIt.hasNext() ) {
COSObject object = doc.getDocument().getObjectFromPool(
xrefEntriesIt.next().getKey() );
if ( object.getDictionaryObject( COSName.SUBTYPE ) == COSName.IMAGE ) {
changeImage( object, doc);
}
}
and method for to change image
private static void changeImage(COSObject obj, PDDocument doc) {
PDXObjectImage imageInPdf =
(PDXObjectImage) PDXObject.createXObject(
(COSStream) obj.getObject());
File inputFile = new File("C:\\temp\\SIGNATURE.jpg");
PDXObjectImage newImage = new PDJpeg(
doc, new FileInputStream(inputFile));
imageInPdf.getCOSStream().replaceWithStream(newImage.getCOSStream());
}
I tested. imageInPdf is rally image from visual appearance of a signed signature field.
now how to remove and add new visual appearance of a signed signature field?

I've just added doc.save(). that's all

Related

ABCPdf - Image not a suitable format

In the end, my goal is to send a raw image data from the front-end, then split that image into however many pages, and lastly send that pdf back to the front-end for download.
But every time I use the theDoc.addImageFile(), it tells me that the "Image is not in a suitable format". I'm using this as reference: https://www.websupergoo.com/helppdfnet/source/5-abcpdf/doc/1-methods/addimagefile.htm
To troubleshoot, I thought that the image might not be rendering correctly, so I added a File.WriteAllBytes to view the rendered image and it was exactly what I wanted, but still not adding to the PDF. I also tried sending the actual path of a previously rendered image thinking that the new image might not have been fully created yet, but it also gave me the same error. Lastly, I thought PNGs might be problematic and changed to JPG but it did not work.
Here is the code:
[HttpPost]
public IActionResult PrintToPDF(string imageString)
{
// Converts dataUri to bytes
var base64Data = Regex.Match(imageString, #"data:image/(?<type>.+?),(?<data>.+)").Groups["data"].Value;
var binData = Convert.FromBase64String(base64Data);
/* Ultimately will be removed, but used for debugging image */
string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string imgName= "Test.jpg";
string filename = Path.Combine(path, imgName);
System.IO.File.WriteAllBytes(filename, binData);
/***********************************************************/
using (Doc theDoc = new Doc())
{
// Using explicit path
theDoc.AddImageFile(#"C:\Users\User\Documents\Test.jpg", 1);
// Using variable
//theDoc.AddImageFile(filename, 1);
// What I really want
//theDoc.AddImageFile(binData , 1);
theDoc.Page = theDoc.AddPage();
theDoc.AddText("Thanks");
Response.Headers.Clear();
Response.Headers.Add("content-disposition", "attachment; filename=test.pdf");
return new FileStreamResult(theDoc.GetStream(), "application/pdf");
}
}
Try something like this (not tested, but cleaned up from my own code):
public int AddImageFile(Doc doc, byte[] data, int insertBeforePageID)
{
int pageid;
using (var img = new XImage())
{
img.SetData(data);
doc.Page = doc.AddPage(insertBeforePageID);
pageid = doc.Page;
doc.AddImage(img);
img.Clear();
}
return pageid;
}
To add a JPEG from a byte array you need Doc.AddImageData instead of Doc.AddImageFile. Note that AddImageFile / AddImageData do not support PNG - for that you would definitely need to use an XImage. The XImage.SetData documentation has the currently supported image formats.

Byte Image Rotation in .Net Core

I've an IFormFile image file (from postman as form data), which I convert into byte array. Before converting it into byte array, I want to rotate it into its actual position (if user input image as 90°(right). I'm implementing web api in asp.net core 2.0.
byte[] ImageBytes = Utils.ConvertFileToByteArray(model.Image);
public static byte[] ConvertFileToByteArray(IFormFile file)
{
using (var memoryStream = new MemoryStream())
{
file.CopyTo(memoryStream);
return memoryStream.ToArray();
}
}
Any help, Thanks in advance.
In my project I need to crop and resize the images users upload. And I am using a fantastic library called ImageSharp from Six Labors. You can use its image processor to do the transformation such as Resize, Crop, Skew, Rotate and more!
Install via NuGet
I am actually using their nightly build through MyGet.
Visual Studio -> Tools -> Options -> NuGet Package Manager -> Package Sources
Hit the "Plus" button to add a new package resource
I typed "ImageSharp Nightly" as the name and put "https://www.myget.org/F/sixlabors/api/v3/index.json" as the source url.
On Browse, search "SixLabors.ImageSharp" (In my case I also need "SixLabors.ImageSharp.Drawing" but in your case you might only need to core library. Always refer back to their documentations).
Crop & Resize
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Formats;
using SixLabors.ImageSharp.Processing;
using SixLabors.ImageSharp.Processing.Transforms;
using SixLabors.Primitives;
using System.IO;
namespace DL.SO.Project.Services.ImageProcessing.ImageSharp
{
public CropAndResizeResult CropAndResize(byte[] originalImage,
int offsetX, int offsetY, int croppedWidth, int croppedHeight,
int finalWidth, int finalHeight) : IImageProcessingService
{
IImageFormat format;
using (var image = Image.Load(originalImage, out format))
{
image.Mutate(x => x
// There is .Rotate() you can call for your case
.Crop(new Rectangle(offsetX, offsetY, croppedWidth, croppedHeight))
.Resize(finalWidth, finalHeight));
using (var output = new MemoryStream())
{
image.Save(output, format);
// This is just my custom class. But see you can easily
// get the processed image byte[] using the ToArray() method.
return new CropAndResizeResult
{
ImageExtension = format.Name,
CroppedImage = output.ToArray()
};
}
}
}
}
Hope this helps you - from a big fan of ImageSharp library!
Magick.NET, The ImageMagick wrapper for .Net Core can be used for many file manipulations, see https://github.com/dlemstra/Magick.NET
byte[] byt = System.IO.File.ReadAllBytes(filePath);
System.IO.MemoryStream ms = new System.IO.MemoryStream(byt);
using (Image img = Image.FromStream(ms))
{
RotateFlipType r = angle == 90 ? RotateFlipType.Rotate90FlipNone : RotateFlipType.Rotate270FlipNone;
img.RotateFlip(r);
img.Save(filePath);
}
Using your existing code you can do the following

inline image is coming as .bin file while sending email Outlook 2016

i am trying to send Inline image in html and it is coming as .bin file
i have already read the answer of this Quesstion
Sending an e-mail with an image inline that is attached comes up as ATT00001 on some computers
but still not able to solve it
string DexuslogoImage2 = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Images\\DexusTenantNotice.png");
string strBody = strBody.Replace("##DexusNoticeLogo##", "cid:Dexuslogo1");
dynamic htmlView = AlternateView.CreateAlternateViewFromString(_Body.ToString(), null, "text/html");
if (!string.IsNullOrEmpty(_EmailLogo)) {
LinkedResource logo = new LinkedResource(_EmailLogo);
logo.ContentId = "Dexuslogo1";
htmlView.LinkedResources.Add(logo);
}
LinkedResource logo1 = new LinkedResource(_EmailLogo1);
logo1.ContentId = "Dexuslogo2";
htmlView.LinkedResources.Add(logo1);
aMessage.AlternateViews.Add(htmlView);
i have found answer .bin file comes when _EmailLogo1 and _EmailLogo are empty so need
to check if it's empty or not !!
dynamic htmlView = AlternateView.CreateAlternateViewFromString(_Body.ToString(), null, "text/html");
if (!string.IsNullOrEmpty(_EmailLogo1)) {
LinkedResource logo = new LinkedResource(_EmailLogo);
logo.ContentId = "Dexuslogo2";
htmlView.LinkedResources.Add(logo);
}
if (!string.IsNullOrEmpty(_EmailLogo))
{
LinkedResource logo1 = new LinkedResource(_EmailLogo1);
logo1.ContentId = "Dexuslogo2";
htmlView.LinkedResources.Add(logo1);
aMessage.AlternateViews.Add(htmlView);
}

Send bitmap parameter to another xaml page

In Windows Phone 8.1 , i have a ListView. My list is populated with an ObservableColection of Pictures. In class Pictures i have pictureName , and bitmapImage.
In ListView_Item_Click , i want to click a Picture and send it to another xaml page.
BitmapImage img = new BitmapImage();
img = ((Picture)e.ClickedItem).Image;//imi selectez imaginea care doresc!!
var image = new Image();
image.Source = img;
Frame.Navigate(typeof(Page2), image); in mainpage.xaml.cs
I wouldn't pass BitmapImage as a parameter of Frame.Navigate - it's not serializable and there will be a problem with SuspensionManager or Resuming/Suspending events.
The solution depends on your images - where to they come from - if it's a file, then you can just pass a path to that file and then in OnNavigated (for example), set the ImageSource from file.
Other method may be to set BitmapImage in target page, before it's navigated to - for example use static property:
public class TargetPage : Page, INotifyPropertyChanged
{
private static BitmapImage bmpImage;
public static BitmapImage BmpImage
{
get { return bmpImage; }
set { bmpImage = value; RaisePropertyChanged("BmpImage"); }
}
// rest of the code
Then you can just set the image before navigating:
TargetPage.BmpImage = img;
Frame.Navigate(typeof(TargetPage));
Also you should remember about Suspending and Resuming events and the case when your app is being terminated while it's Suspended. In every case you should somehow remember the source of the image - using SuspensionManager, PageState, Settings or other method.

How can I insert an image with iTextSharp in an existing PDF?

I have an existing PDF and I can use FdFWriter to input to text boxes. It works well. Now I have an image. I have read the documentation and looked at many examples but they all create new documents and insert an image. I want to take an existing PDF and insert an image into either an image field or as the icon image of a button. I have tried but it corrupts the document.
I need to be able to take an existing document and put an image on it. I do not want to open, read, replace, and delete the original. This original changes and the name "original" only means the source file in this context. There are many PDF files like this that need an image.
Thank you for any help.
Edit - I am very thankful for the code below. It works great, but the problem for me is that the existing PDF has digital signatures on it. When the document is copied like this (into result.pdf) those signatures, while still present, have a different byte count or other item that is corrupted. This means the signatures, while they show up on result.pdf, have an icon next to them that state "invalid signature."
In case it matters I am using a Topaz signature pad to create my signatures, which has it's own security. Merely copying the PDF will not corrupt it but the process below will.
I am trying to put the image on the existing document, not a copy of it, which in this case matters.
Also, by signature, I mean handwritten, not pin numbers.
Thank you again.
EDIT - Can PdfSignatureAppearance be used for this?
EDIT - I seem to be able to do it with:
var stamper = new PdfStamper(reader, outputPdfStream,'1',true);
If you want to change the contents of an existing PDF file and add extra content such as watermarks, pagenumbers, extra headers, PdfStamper is the object you need. I have successfully used the following code to insert an image into an existing pdf file to a given absolute position:
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
class Program
{
static void Main(string[] args)
{
using (Stream inputPdfStream = new FileStream("input.pdf", FileMode.Open, FileAccess.Read, FileShare.Read))
using (Stream inputImageStream = new FileStream("some_image.jpg", FileMode.Open, FileAccess.Read, FileShare.Read))
using (Stream outputPdfStream = new FileStream("result.pdf", FileMode.Create, FileAccess.Write, FileShare.None))
{
var reader = new PdfReader(inputPdfStream);
var stamper = new PdfStamper(reader, outputPdfStream);
var pdfContentByte = stamper.GetOverContent(1);
Image image = Image.GetInstance(inputImageStream);
image.SetAbsolutePosition(100, 100);
pdfContentByte.AddImage(image);
stamper.Close();
}
}
}
When you insert the image you have the possibility to resize it. You can take a look at transformation matrix in the iTextSharp documentation.
Here is a similar example whichi inserts an image on the page using the stamper:
Gmane iTex Mailing List Post
I could solve my problem by simply adding following lines to my signing code to add image
var image = iTextSharp.text.Image.GetInstance(#"C:\Users\sushil\Documents\sansign.jpg");
appearance.Acro6Layers = true;
appearance.SignatureGraphic = image;
appearance.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.GRAPHIC_AND_DESCRIPTION;
As I was signing document with visible digital signature , now I can have both image and digital signature properties side by side
in the .net core6 that uses DDD try this declare class in Infrastructure Layer
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
public async Task<string> SignatureToPdf(string pathPdfFile, string
pathSignatureImage, string pathOutputName)
{
var webRootPath = hostingEnvironment.ContentRootPath;
if (!File.Exists(Path.Combine(webRootPath, pathPdfFile))) return
null;
await using Stream inputPdfStream =
new FileStream(Path.Combine(webRootPath, pathPdfFile),
FileMode.Open, FileAccess.Read, FileShare.Read);
await using Stream inputImageStream =
new FileStream(Path.Combine(webRootPath, pathSignatureImage), FileMode.Open, FileAccess.Read, FileShare.Read);
await using Stream outputPdfStream =
new FileStream(Path.Combine(webRootPath, pathOutputName),
FileMode.Create, FileAccess.Write, FileShare.None);
var reader = new PdfReader(inputPdfStream);
var stamper = new PdfStamper(reader, outputPdfStream);
var pdfContentByte = stamper.GetOverContent(1);
var image = Image.GetInstance(inputImageStream);
image.SetAbsolutePosition(100, 100);
pdfContentByte.AddImage(image);
stamper.Close();
return "ok";
}
pdftk can do this. It's not a library but you can easily call it from your code as a .exe.
See stamp and background commands:
http://www.pdflabs.com/docs/pdftk-man-page/
ref: How to do mail merge on top of a PDF?

Resources