Как отделить содержимое тела с фиксированным заголовком и нижним колонтитулом для нескольких страниц

У меня есть три отдельных раздела: header, body и footer для создания pdf.

Часть заголовка всегда будет находиться наверху каждой страницы, и она будет исправлена.

 ______________________
|        header        |
|______________________|

Проблема заключается в содержании тела, если контент большой, он перейдет на вторую страницу.

 ______________________
|                      |
|                      |
|        body          |
|                      |
|                      |
|______________________|

Нижняя часть будет всегда находиться внизу каждой страницы, и она также будет исправлена.

 ______________________
|        footer        |
|______________________|

Итак, если контент большой, и если две страницы созданы, я должен получить две страницы:

 ______________________
|        header        |
|______________________|
|                      |
|                      |
|        Body Part1    |
|                      |
|                      |
|______________________|
|        footer        |
|______________________|

И

 ______________________
|        header        |
|______________________|
|                      |
|                      |
|        Body part2    |
|                      |
|                      |
|______________________|
|        footer        |
|______________________|

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

Я использую laravel dompdf

Любая помощь будет оценена.

Ответы

Ответ 1

Я снова проверил этот полезный ответ: fooobar.com/questions/18496/... и с некоторыми изменениями и внешним тегом div. Он работает для меня.

Я не знаю, как laravel dompdf преобразует этот html в pdf, но он работает для меня.

Вот мой код laravel

Route::get('/', function () {
    $output = '<style>';
    $output .= '
        .divFooter {position: fixed;bottom: 20;text-align:center;}
                ';
    $output .= '</style>';
    $output .= '<div class="divFooter" style="color:red;"><h1>This is footer</h1></div>';
    $output .= '<table width="100%"><thead><tr><th><div style="color:red;"><h1>This is header</h1></div><th></tr></thead>';
    $output .= '<tbody><tr><td>';
    $output .= 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</td></tr>
      .........................
      .........................
      .........................
    ';
    $output .= '</tbody></table>';
    $pdf = App::make('dompdf.wrapper');
    $pdf->loadHTML($output);
    return $pdf->stream();
});

Какая генерация PDF выглядит следующим образом: http://content.screencast.com/users/Niklesh2/folders/Jing/media/13bb7a6f-f280-46db-94df-1af6270b4b02/2016-08-10_1713.png

Мне жаль, что я не могу сказать вам, как это работает. Но может быть полезно для тех, кто работает в laravel dompdf.

приветствия!!

Ответ 2

HTML принимает постоянную непрерывную последовательность элементов, в то время как печатные страницы требуют разделить это содержимое на разделы. Лучшее, что может сделать интерпретатор, если вы не говорите ему иначе, - это разделять элементы на страницы, чтобы большинство из них находилось на одной странице.

Эта очень исчерпывающая статья о SmashingMagazine расскажет вам о том, как использовать CSS для разработки HTML для печати. ​​

Самое главное для вашего вопроса, он подробно остановится на @page регионах на аккуратном листе. Для вас, скорее всего, будут области top-center и bottom-center (которые, в отличие от того, что вы могли бы подумать, глядя на документ, могут очень распространяться на всю ширину документа).

Используя эти регионы, вы можете определить верхний и нижний колонтитулы с помощью CSS и даже стилизовать их в зависимости от того, на какой стороне они находятся, если вы разрабатываете книгу. Они работают, добавляя контент непосредственно на CSS, поэтому для работы HTML не требуется разметка.

/* print a centered title on every page */
@top-center {
  content: "Title";
  color: #333;
  text-align: center;
}

/* print the title on the left side for left-hand pages, and vice versa */
@page:left {
  @top-left {
    content: "Title";
    color: #333;
  }
}
@page:right {
  @top-right {
    content: "Title";
    color: #333;
  }
}

Несмотря на то, что вы не используете для вас проблему с laravel, ни один браузер, который я нахожу, не будет распечатывать эти регионы, поэтому это будет не так просто для обычных стилей печати. ​​


Хотя вы можете многое сделать с CSS, у вас может быть слишком сложный контент, чтобы создать его выше. В этом случае вы можете использовать элемент с свойством position:fixed, который будет отображаться в верхней/нижней части каждой страницы, в зависимости от того, как вы его стиль, например, следующим образом:

@media print {
  header {
    position: fixed;
    top: 0;
  }
  footer {
    position: fixed;
    bottom: 0;
  }
}

HTML:

<body>
  <header>
      above the content on screen, and on the top of every printed page
  </header>
  <main>
      content that is flowing and behaving as you would expect it
  </main>
  <footer>
      below the content on screen, and on the bottom of every printed page
  </footer>
</body>

Ответ 3

Попробуйте приведенный ниже код в полном виде.

header{
	height: 80px;
	border:1px solid red;
	position: fixed;
	width: 100%;
	top:0;
	background-color: red;
}
.content{
	border: 2px solid #000;
	margin-top: 80px;
	height: 100%;
	width: 100%;
}
footer{
	height: 80px;
	border:1px solid red;
	position: fixed;
	bottom: 0;
	width: 100%;
	background-color: red;
}
<body>

<header>
	<h1>Header</h1>
</header>

<div class="content">
	<h1>Content</h1>
	<p>one Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
	tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
	quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
	consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
	cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
	proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>

	<p>2 Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
	tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
	quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
	consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
	cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
	proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>

	<p>3 Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
	tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
	quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
	consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
	cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
	proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
	<p>4 Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
	tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
	quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
	consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
	cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
	proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
	<p>5 Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
	tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
	quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
	consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
	cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
	proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
	<p>6 Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
	tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
	quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
	consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
	cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
	proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
	<p>7 Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
	tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
	quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
	consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
	cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
	proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</div>

<footer>
	<h1>Footer</h1>
</footer>


</body>

Ответ 4

В основном, этот тип приложений, называемый Single Page Application

> Пожалуйста, используйте силу AngularJs в этом типе требований, он имеет прочность маршрутизации.

<html>

   <head>
      <title>Angular JS Views</title>
      <script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
      <script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular-route.min.js"></script>
   </head>

   <body>
      <h2>AngularJS Sample Application</h2>
      <div ng-app = "mainApp">
         <p><a href = "#addStudent">Add Student</a></p>
         <p><a href = "#viewStudents">View Students</a></p>
         <div ng-view></div>

         <script type = "text/ng-template" id = "addStudent.htm">
            <h2> Add Student </h2>
            {{message}}
         </script>

         <script type = "text/ng-template" id = "viewStudents.htm">
            <h2> View Students </h2>
            {{message}}
         </script>
      </div>

      <script>
         var mainApp = angular.module("mainApp", ['ngRoute']);
         mainApp.config(['$routeProvider', function($routeProvider) {
            $routeProvider.

            when('/addStudent', {
               templateUrl: 'addStudent.htm',
               controller: 'AddStudentController'
            }).

            when('/viewStudents', {
               templateUrl: 'viewStudents.htm',
               controller: 'ViewStudentsController'
            }).

            otherwise({
               redirectTo: '/addStudent'
            });
         }]);

         mainApp.controller('AddStudentController', function($scope) {
            $scope.message = "This page will be used to display add student form";
         });

         mainApp.controller('ViewStudentsController', function($scope) {
            $scope.message = "This page will be used to display all the students";
         });

      </script>

   </body>
</html>