In paper we consider a code-formatting problem. A novel concept of declarative printers is introduced. These devices can perform formatting in accordance with the style of the rest of the source code. For this purpose, declarative formatters extract syntactic templates from the sample code and use them to construct a new representation of the input program. A proposed solution produces optimal program presentation in polynomial time. It is achieved by using polynomial-time pretty-printer combinators and introducing a partial order on text representations. We also present the results of evaluating the approach in the Java and Haskell languages. The development of a declarative printer for simple imperative language While is described. A comparison with modern IDEs code formatters is also presented.