2015-06-16 3 views
0

Я использую таблицу для отображения данных легенды. Страница находится в ландшафтном режиме. Я хотел бы ограничить строки таблицы до 15 на столбец. 2 столбца на страницу, а затем создается новая страница и т. Д. Это текущий выход. currentoutputКак ограничить строки таблицы на страницу с помощью PDFsharp?

Вот макет того, что я хотел бы, чтобы он выглядел, когда есть больше данных. Если более 30 элементов, то необходимо создать новую страницу. whatIneedittolooklike

код в контроллере

[HttpPost] 
    public PDF Post([FromBody]List<Data> data) 
    { 

     try 
     { 
      // Get some file names 

      string filePath = @"~\tempPdfs\"; 
      string completeFilePath = HttpContext.Current.Server.MapPath(filePath); 

      var directory = new DirectoryInfo(completeFilePath); 
      var fileName = (from f in directory.GetFiles("*.pdf") 
          orderby f.LastWriteTime descending 
          select f).First(); 
      // Open the output document 


      PdfDocument outputDocument = new PdfDocument(); 


      // Open the document to import pages from it.. 
      PdfDocument inputDocument = PdfReader.Open(fileName.FullName, PdfDocumentOpenMode.Import); 

      // Iterate pages 
      int count = inputDocument.PageCount; 
      for (int idx = 0; idx < count; idx++) 
      { 
       // Get the page from the external document... 
       PdfPage page = inputDocument.Pages[idx]; 
       // ...and add it to the output document. 
       outputDocument.AddPage(page); 
      } 


      //Create an Empty Page 
      PdfPage pdfpage = outputDocument.AddPage(); 
      pdfpage.Size = PageSize.Letter; // Change the Page Size 
      pdfpage.Orientation = PageOrientation.Landscape;// Change the orientation property 

      //Get an XGraphics object for drawing 
      XGraphics xGrap = XGraphics.FromPdfPage(pdfpage); 

      //Create Fonts 
      XFont titlefont = new XFont("Calibri", 20, XFontStyle.Regular); 
      XFont tableheader = new XFont("Calibri", 15, XFontStyle.Bold); 
      XFont bodyfont = new XFont("Calibri", 11, XFontStyle.Regular); 

      //Draw the text 
      //double x = 250; 
      double y = 50; 
      //Title Binding 
      XTextFormatter textformater = new XTextFormatter(xGrap); //Used to Hold the Custom text Area 

      foreach (var item in data) 
      { 
       string colorStr = item.Color; 

       Regex regex = new Regex(@"rgb\((?<r>\d{1,3}),(?<g>\d{1,3}),(?<b>\d{1,3})\)"); 
       //regex.Match(colorStr.Replace(" ", "")); 
       Match match = regex.Match(colorStr.Replace(" ", "")); 
       if (match.Success) 
       { 
        int r = int.Parse(match.Groups["r"].Value); 
        int g = int.Parse(match.Groups["g"].Value); 
        int b = int.Parse(match.Groups["b"].Value); 

        y = y + 30; 
        XRect ColorVal = new XRect(85, y, 5, 5); 
        XRect NameVal = new XRect(100, y, 250, 25); 

        var brush = new XSolidBrush(XColor.FromArgb(r, g, b)); 
        xGrap.DrawRectangle(brush, ColorVal); 
        textformater.DrawString(item.Name, bodyfont, XBrushes.Black, NameVal); 

       }; 
      }; 



      // Save the document... 
      var dt = DateTime.Now.ToString("g").Replace('/', '-').Replace(':', '-'); 
      var filename = string.Format("{0}-{1}.pdf", "PdfSharpResult", dt); 
      string physicalPath = HttpContext.Current.Server.MapPath("/completePdfs"); 
      string relativePath = Path.Combine(physicalPath, filename).Replace("\\", "/"); 
      var pdfName = relativePath; 
      outputDocument.Save(pdfName); 
      // ...and start a viewer. 
      Process.Start(pdfName); 

      return new PDF 
      { 
       FileName = pdfName, 
       FileNameEncoded = HttpUtility.UrlEncode(pdfName) 
      }; 


     } 
     catch (Exception ex) 
     { 
      Debug.Print(ex.ToString()); 
      return new PDF 
      { 
       Error = ex.ToString() 
      }; 
     } 

    } 
+0

Можете ли вы показать код, в котором вы создаете таблицу, и назначить ему строки – stuartd

+0

только что добавили весь контроллер – texas697

+0

Я не верю, что PDFSharp имеет встроенную поддержку таблиц, и вам нужно будет управлять макетом самостоятельно или использовать что-то как MigraDoc – stuartd

ответ

1

Где проблема?

Вам нужна переменная X. После 15 строк вы возвращаете Y и приращение X.

После 30 строк вы перезапускаете X и Y, добавляете новую страницу, получаете новую XGrap для этой страницы и делаете свежий XTextFormatter и продолжаете это до тех пор, пока список не будет выполнен.

Счетчик строк, вероятно, упростит ситуацию.

Непроверенные код, показывающий цикл, который создает страницы по мере необходимости и ухаживает за второй колонке:

PdfPage pdfpage; 
XGraphics xGrap; 
XTextFormatter textformater; 

//Create Fonts 
XFont titlefont = new XFont("Calibri", 20, XFontStyle.Regular); 
XFont tableheader = new XFont("Calibri", 15, XFontStyle.Bold); 
XFont bodyfont = new XFont("Calibri", 11, XFontStyle.Regular); 

//Draw the text 
double x = 0; 
double y = 50; 
//Title Binding 

int index = 0; 
foreach (var item in data) 
{ 
    if (index % 30 == 0) 
    { 
     y = 50; 
     x = 0; 
     // Start a new page. 
     //Create an Empty Page 
     pdfpage = outputDocument.AddPage(); 
     pdfpage.Size = PageSize.Letter; // Change the Page Size 
     pdfpage.Orientation = PageOrientation.Landscape;// Change the orientation property 

     //Get an XGraphics object for drawing 
     xGrap = XGraphics.FromPdfPage(pdfpage); 
     textformater = new XTextFormatter(xGrap); //Used to Hold the Custom text Area 
    } 
    else if (index % 15 == 0) 
    { 
     // Start a new column. 
     y = 50; 
     x = 400; 
    } 
    ++index; 

    // Previous code stays here, but must use x in new XRect(...) 

    string colorStr = item.Color; 

    Regex regex = new Regex(@"rgb\((?<r>\d{1,3}),(?<g>\d{1,3}),(?<b>\d{1,3})\)"); 
    //regex.Match(colorStr.Replace(" ", "")); 
    Match match = regex.Match(colorStr.Replace(" ", "")); 
    if (match.Success) 
    { 
     int r = int.Parse(match.Groups["r"].Value); 
     int g = int.Parse(match.Groups["g"].Value); 
     int b = int.Parse(match.Groups["b"].Value); 

     y = y + 30; 
     XRect ColorVal = new XRect(x + 85, y, 5, 5); 
     XRect NameVal = new XRect(x + 100, y, 250, 25); 

     var brush = new XSolidBrush(XColor.FromArgb(r, g, b)); 
     xGrap.DrawRectangle(brush, ColorVal); 
     textformater.DrawString(item.Name, bodyfont, XBrushes.Black, NameVal); 

    }; 
}; 

х = 400 только предположение, чтобы вы начали. Заголовки таблицы отсутствуют.

+0

Проблема в том, что я потерян. можете ли вы привести пример того, что вы предлагаете? – texas697

+0

Я бы использовал цикл while? – texas697

+0

Я обновил свой пост. Никакая гарантия не компилируется, это просто означает показать, как я буду делать цикл. –

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