Rank: Newbie
Groups: Registered
Joined: 3/3/2017(UTC) Posts: 5   Thanks: 2 times
|
Hi everybody, I have a problem. My application must insert an image (bmp) into existing pdf and for this there are two options: 1. To put the image on the first sheet of the document 2. A new sheet is inserted at the beginning of the original document and the image is embedded in it The problem is at (1), in some pdf documents (which seem to have layers) when I carry out the whole process and save the pdf in a file, I get a pdf with the image embedded (correct), but from the original document only a part is seen, it lacks the content. However, with option (2) the same document performs well. The weird thing is that it does not happen with all documents, that is, in some the two options work correctly Code:
private void GenerateOutputDocument()
{
// Obtenemos el documento
Document = GetDocument();
// Genera la imagen de la etiqueta
Bitmap bmp = GetTagImage();
var pdfBitmap = CreateBitmap(bmp);
// Create image object and set previously created bitmap
var img = PdfImageObject.Create(Document);
img.SetBitmap(pdfBitmap);
//Move image object to 0,0 and set it's size to 1px;
img.SetMatrix(1, 0, 0, 1, 0, 0);
// Calculamos los tamaños para centrar la etiqueta en el documento
var width = bmp.Width / 2;
var height = bmp.Height / 2;
var widthOverflow = (Document.Pages[0].Width / 2) - (width / 2); // Centrado horizontalmente
var heightOverflow = 5; // Colocado abajo
// Colocamos la etiqueta en su posición final
img.Transform(width, 0, 0, height, widthOverflow, heightOverflow);
// Insertamos la imagen en la primera página del documento
Document.Pages[0].PageObjects.InsertObject(img);
// Guardamos el fichero generado en una ubicación temporal
Document.Pages[0].GenerateContent();
_tempFile = _tempFile ?? FileUtils.GetTempFile(extension: "pdf", subfolder: "pdf_with_tag");
Document.Save(_tempFile, SaveFlags.NoIncremental);
}
private PdfDocument GetDocument()
{
List<PdfDocument> generatedDocuments = new List<PdfDocument>();
// Creamos la primera página vacía si es necesario
if (Extracto.TagInNewPage)
{
var blankPage = PdfDocument.CreateNew();
AddNewPage(blankPage);
generatedDocuments.Add(blankPage);
}
// Obtenemos el pdf original
generatedDocuments.Add(PdfDocument.Load(Extracto.PdfFilePath()));
// Unimos todo en un mismo documento
var resultDocument = PdfDocument.CreateNew();
foreach (var pdfDoc in generatedDocuments)
resultDocument.Pages.ImportPages(pdfDoc, null, resultDocument.Pages.Count);
return resultDocument;
}
private void AddNewPage(PdfDocument doc)
{
int pageIndex = 0;
var pdf_width = 595;
var pdf_height = 842;
doc.Pages.InsertPageAt(pageIndex, pdf_width, pdf_height);
doc.Pages[pageIndex].GenerateContent();
}
Edited by moderator Monday, July 13, 2020 7:27:51 PM(UTC)
| Reason: Not specified
|