2015-09-23 5 views
0
int iNbFichier = 0; 
while (File.Exists(folderName + "/" + newFile + ((iNbFichier > 0) ? "_" + iNbFichier.ToString() : "") + ext)) 
{ 
    iNbFichier++; 
} 

// open the reader 
PdfReader reader = new PdfReader(oldFile); 
document = new Document(PageSize.A4, 5, 5, 120, 60); 

// open the writer 
FileStream fs = new FileStream(folderName + "/" + newFile + ((iNbFichier > 0) ? "_" + iNbFichier.ToString() : "") + ext, FileMode.Create, FileAccess.Write); 
PdfWriter writer = PdfWriter.GetInstance(document, fs); 
document.Open(); 

int numberPage = reader.NumberOfPages;        

// the pdf content 
PdfContentByte cb = writer.DirectContent; 

for (int i = 1; i <= reader.NumberOfPages; i++) 
{ 
     // create the new page and add it to the pdf 
     PdfImportedPage page = writer.GetImportedPage(reader, i); 
     cb.AddTemplate(page, 0, 0); 
     if(i != numberPage) document.NewPage(); 
     cb = writer.DirectContent; 
} 

if (availableSpace < 90) 
{ 
     writer.NewPage(); 
     cb = writer.DirectContent; 
}        

// select the font properties 
BaseFont bf = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); 
cb.SetColorFill(BaseColor.BLACK); 
cb.SetFontAndSize(bf, 8); 

// write the text in the pdf content 
cb.BeginText(); 
string text = "Le " + DateTime.Now.ToString().Substring(0, 10); 
// put the alignment and coordinates here 
cb.ShowTextAligned(1, text, 455, 750, 90); 
cb.EndText(); 

// write the text in the pdf content 
cb.BeginText(); 
text = salarie.NOM + " " + salarie.PRENOM; 
// put the alignment and coordinates here 
cb.ShowTextAligned(1, text, 465, 750, 90); 
cb.EndText(); 

// write the text in the pdf content 
cb.BeginText(); 
text = "Signature :"; 
// put the alignment and coordinates here 
cb.ShowTextAligned(1, text, 475, 750, 90); 
cb.EndText(); 

iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(globale.EncodePhoto(this.signature)); 
//img.SetAbsolutePosition(485, 750); 

img.Border = 0; 

//Resize picture to fit 380x150 ratio if its bigger 
int intMaxWidth = 100; 
int intMaxHeight = 50; 
BitmapImage bmpMain = this.signature; 
if (bmpMain.Height > intMaxHeight || bmpMain.Width > intMaxWidth) 
{ 
     double dblHeightRatio = Convert.ToDouble(intMaxHeight)/Convert.ToDouble(bmpMain.Height); 
     double dblWidthRatio = Convert.ToDouble(intMaxWidth)/Convert.ToDouble(bmpMain.Width); 
     double dblScaleRatio; 

     //Use the smaller ratio 
     if (dblHeightRatio > dblWidthRatio) 
     { 
      dblScaleRatio = dblWidthRatio; 
     } 
     else 
     { 
      dblScaleRatio = dblHeightRatio; 
     } 

     int intNewHeight = Convert.ToInt32(bmpMain.Height * dblScaleRatio); 
     int intNewWidth = Convert.ToInt32(bmpMain.Width * dblScaleRatio); 

     img.ScaleAbsolute((float)intNewWidth, 
                (float)intNewHeight); 
} 

img.SetAbsolutePosition(480, 700); 
img.RotationDegrees = 90; 

cb.AddImage(img);        

// close the streams and voilá the file should be changed :) 
document.Close(); 
fs.Close(); 
writer.Close(); 
reader.Close(); 

Если доступное пространство на мой стол и нижний колонтитулы является < до 90, то я хочу, чтобы создать новую страницу и поставить свою подпись на последней странице, которая создается.Добавить страницу в существующий PDF документ с помощью C# и iTextSharp

Но мой код не работает. Кто-то может помочь мне решить эту проблему?

Мое приложение предназначено для планшетов, поэтому для устранения дублирования требуется слишком много ресурсов для использования в этом случае.

+0

Возможный дубликат [Вставить страницу в существующий PDF с помощью itextsharp] (http://stackoverflow.com/questions/6657899/insert-page-into-existing-pdf-using-itextsharp) –

+0

Я уже пробовал это, но он тоже не работает – Moussawi

+0

Вызывает ли это исключение? –

ответ

0
string oldFile = "Tmp.pdf"; 
string newFile = nomFichier = DateTime.Now.ToString(). 
           Substring(0,10).Replace('/','-') + 
           "_" + salarie.NOM + "_" + salarie.PRENOM; 
string ext = ".pdf"; 
string folderName = "FICHE_EPI"; 

//Si le tableau est trop bas pour faire passer la signature 
if (availableSpace < 90) 
{ 
    var tempFileLocation = @"Tmp2.pdf"; 
    var bytes = File.ReadAllBytes(@"Tmp.pdf"); 

    using (var reader1 = new PdfReader(bytes)) 
    { 
     var numberofPages = reader1.NumberOfPages; 
     var pages = 1; 

     if (pages != 0) 
     { 
      using (var fileStream = new FileStream(
        tempFileLocation, 
        FileMode.Create, 
        FileAccess.Write)) 
      { 
       using (var stamper = new PdfStamper(reader1, fileStream)) 
       {            
        var rectangle = reader1.GetPageSize(1); 
        for (var i = 1; i <= pages; i++) 
         stamper.InsertPage(numberofPages + i, rectangle); 
       } 
      } 
     } 
    } 
    File.Delete(@"Tmp.pdf"); 
    File.Move(tempFileLocation, @"Tmp.pdf"); 

Это решение моих проблем.

Смежные вопросы